Efficiency of iteration over arrays?

I got the following question on email:

Question:

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:

  1. Foreach over an int array

  2. Simple for over an int array

  3. For over an int array, hoisting out the length value

On questions such as these, there are two ways to find the answer. The first is to build the code and look at the generated IL (or the resulting assembly, remembering that you get debug code if you run in the debugger. Attach to a running process, and then you get the optimized native code), or to time the code with a stopwatch.

In this case, I chose the IL approach, because it was quicker. For arrays, versions #1 and #2 produce similar IL, and should produce very similar execution speed (I'm too lazy to actually time them today). So, I would choose the foreach version unless I needed the index.

In fact, I would advocate this position even if for loops are faster, to avoid the sin of premature optimization. It remains true that only 10% of the code needs optimization, and that algorithmic efficiency is often the driving factor.

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...

Code

 

 int [] foo = new int[100];
 // version 1:
 foreach ( int i in foo)
   Console.WriteLine( i.ToString( ));
  
 // Version 2:
 for ( int index = 0;
   index < foo.Length;
   index++ )
   Console.WriteLine( foo[index].ToString( ));
  
 // Version 3:
 int len = foo.Length;
 for ( int index = 0;
   index < len; 
   index++ )
   Console.WriteLine( foo[index].ToString( ));