Question

This is a really nit-picky question, but curiosity got the better of me.

Does a for loop re-evaluate the RHS condition each time the loop executes? See below.

for(int i = 0; i < collection.Count; i++)
{
}

Is it good practice throughout your code base to do the following?

for(int i = 0, n = collections.Count; i < n; i++)
{
}

Or does the compiler do these kind of optimisations / they're negligible (even with a huge code base)?

Was it helpful?

Solution

The condition will be reevaluated before every iteration (unless the compiler detects that the condition is constant), and it is acceptable to write code that depends on this (such as calling a function whose return value will be different each time). Thus, if you have a condition that is expensive to evaluate and you are sure it will remain constant, it is indeed a good idea to evaluate it once, before the loop. However, for most standard collection types, Count is such a fast operation that the negligible performance gain won't be worth the reduced readability.

OTHER TIPS

if the right of the condition is constant (so it doesn't change in the loops internals) I believe the optimizer moves the collections.Count outside the top of the loop. If the collection is modified in the loop it would evaluated every-time.

if you used a foreach you will notice that you can't change the enumerator inside the loop because foreach uses this optimization to be a quicker loop....

You could always write a small demo app with a couple of loops one that modifies within the loop and one that doesn't and then run ildasm on it and see what code gets generated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top