Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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++)
{
   ...
}

vs.

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.

share|improve this question
add comment

1 Answer 1

up vote 13 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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