Should I care about moving invariants out of cycle scope if it worsens code readability?

Let's take a look at a simple example:

for (var i = 0; i < collection.Count; i++)


var collectionCount = collection.Count;
for (var i = 0; i < collectionCount; i++)

The performance of second piece of code is better or equal to first one. It will be equal only if collection is fixed-size and Count is not calculated every time. It will be much better if, for example, collection is Linked List which doesn't cache somewhere its Length.

I understand that second approach will unlikely kill my application performance (it is much more likely some inefficient SQL query will) but at the same time I don't feel comfortable when I write second piece of code as I miss (small) optimization. But at the same time from readability point of view I like the first piece of code more (less lines of code, less variables).

I guess it is minor thing and may be it doesn't worth discussing but I would like to hear your opinion.

1 Answer 1


Almost always the answer to this kind of thing is to leave it to the compiler. I would recommend you write the most readable and maintainable code you can and don't worry about this kind of micro-optimisation. Modern compilers are more than capable of make this sort of optimisation on their own.

If and only if you get to the point where you need to make the code run faster, then profile the code, looking at as much of the system as possible and then decide where to start trying to optimise. You will usually find that 80% of the time is spent in a tiny fraction of the code, and this will form a natural point to optimise.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.