One statement that I have heard incessantly is that foreach over an array is slower than for (int i = 0; i < array.Length; i++)
.
Finally, some good people have debunked this myth:
- Kevin Ransom – To foreach or not to foreach, that is the question.
- Eric Gunnerson – Efficiency of iteration over arrays
I personally find it SO much nicer to look at code like:
foreach (int i in array)
{
Console.WriteLine(i.ToString());
}
as opposed to:
for (int i = 0; i < foo.Length; i++)
{
int item = foo[index];
Console.WriteLine(item.ToString());
}
mostly because the first code chunk is a lot more compact, and I think more clearly states its purpose.