Dave Veeneman said:
In a for-loop, is a calculated expression re-calculated on each pass through
the loop, or only once, when the loop is initialized?
The conditional to break out of the for-loop is executed every pass through
the loop. So to answer your question,
for (int i = 0; i < myArray.Length - 1; i++)
Performs a subtraction myArray.Length - 1 times.
int n = myArray.Length - 1;
for (int i = 0; i < n; i++)
Performs a subtraction once.
In general, its advisable to move invariant logic out of the loop conditional.
Normally, it makes little difference when you're looping over the .Length of
an array, because the IL is optimized for this situation:
for ( int i = 0; i < myArray.Length; ++i)
If you look at the difference between this statement, and what you might
think would be a faster statement in,
for ( int i = 0, iMax = myArray.Length; i < iMax; ++i)
You'll find that the IL of the former executes the IL instruction, ldlen, once
each time through the loop, whereas the latter executes ldlen once before
entering the loop and stores it on the stack. Instead of calling ldlen, the
second loop looks-up the length in the stack on each iteration.
On the other hand, as soon as you start doing arithmetic operations on
the length, the iterations of the loop multiply the number of operations
being performed. Thus, whenever operations on the length must be
performed, and the length if fixed, it's a good idea to move it outside
of the loop.
What's more, take a quantity that many developers might think of as being
equivalent to an array's Length -- the Count property of a Collection like
ArrayList. What is the cost of having Count in the conditional of a for-loop
you may ask?
Count is a virtual property, so there is very little in the way of optimization of
IL here. A callvirt operation has to walk the vtable of (potentially) several
accessor methods. Thus, the innocuous-looking access of the Count on
a collection is easily one of the more expensive choices a developer can
undertake in their for-loop conditionals.
Derek Harmon