Loop optimization and .Net JIT Compiler

The other day, a colleague asked me a performance question involving loops and optimization.

The question was as follows:

When looping thru an array in a for loop, should the array's upper bound calculation (array.length) be placed in a separate variable prior to the start of a loop so that the expression does not get evaluated each time thru the loop.

For example:

int l = theArray.length;
for(int i = 0; i < l; i++){
  …
}

vs.

for(int i = 0; i < theArray.length; i++){
  …
}

 

On the surface, this seems to make perfect sense; however, I seemed to remember reading something that suggested that the optimal solution was actually the second, because the compiler already has an algorithm for dealing with this. 

After several minutes of debate, we decided to check the web, and found this interesting article  by Emmanuel Schanzer of Microsoft which suggests that “optimizations like this haven't been helpful for nearly 10 years: modern compilers are more than capable of performing this optimization for you. In fact, sometimes things like this can actually hurt performance.”

Although this sounds counter-intuitive, it really makes sense once you read the article and think about it.

The moral of this story?  Don't try to out think the compiler.