Which one of these three loops is the most efficient? How can I prove the answer?
I've listed the source code below. The three loops are:
-
Foreach over an int array
-
Simple for over an int array
-
For over an int array, hoisting out the length value
...
The third option is to be avoided. The JIT looks for the pattern in version #2, and knows how to optimize it. If you pull the value out into a temporary, it may not optimize it. Of course, you know that because you've been measuring your important scenarios...
via [Eric Gunnerson's C# Compendium]
Hoisting the Length value is ill-advised? Surprising; I'll have to change my habits.