Enumerating array using for vs. foreach

Enumerating array using for vs. foreach

What is the difference between enumerating an array using forversus foreach?

What is the recommended practice and why?

Here is an example:

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

for (int i=0; i<assemblies.Length; i++)

DoSomething(assemblies[i]);

foreach (Assembly a in assemblies)

DoSomething(a);

Answer (from one of the perf architects on the CLR team):

The code gen is basically identical... guidance is to use foreach for clarity unless you plan to modify the contents of the array as you go, in which case for is required. Enumerators are not created in the array case. Note this analysis is not applicable to the collection class case, this is for arrays.

G_M001_IG05:IN0011: 000029 mov ECX, gword ptr [classVar[0x5b9d1994]] // we now have the power to get the stdout stream into ECXIN0012: 00002F mov EDX, ESI // get the string we saved before set it up as an argIN0013: 000031 call dword ptr [(reloc 0x3a80014)]System.IO.TextWriter.WriteLine(ref) // write the stringIN0014: 000037 add EBX, 1 // ebx has 'i' in it remember, upcountIN0015: 00003A cmp dword ptr [EDI+4], EBX // test the current 'i' against the lengthIN0016: 00003D jg SHORT G_M001_IG03 //loop until done