SYSK 132: Loop Performance Comparison -- foreach vs. for

Do you think there is a performance difference between the following two loops?

foreach (int x in _data)

{

            . . .

}

 

vs.

for (int i = 0; i < _data.Count; i++)

{

            . . .

}

 

My tests show that foreach is slower than the for loop.  The larger the collection you’re looping through, the greater is the performance difference…

 

With 1 mln records, it’s about 2 times slower; at 10 mln records it’s about 3.5-4 times slower.  Having said that, we’re still talking about milliseconds; so in comparison with the other work your code is executing in the loop, the difference in the actual loop performance is negligible.