I had a small experiment to prove the point under discussion, I have a table accounts in SQL Server database, I added 20000 rows into the table with 9 columns and approximately 1 Kilobyte of data per record. After loading into my Business layer i am converting it back to a DTO, and returning to my web service. Just to test the performance I added two performance counters, one for “for each” loop and one for “for loop”, The results are obvious, foreach loop took 107 milliseconds to execute the same process, while classic for loop took 14 milliseconds.
Now why does this happen, lets get a bit deeper.
The for loop version uses enough stack space for only two local variables (counter and i). The Foreach version uses stack space for four locals (item, AccountList object, and two compiler-generated temporaries).
When a method is called in the CLR, all of the memory required for the locals is allocated upon the stack. As this takes place on the stack, this process is fast, but it is not free. That is why the foreach-loop will incur a small cost due to its extra two local variables.
There is something else, which changes the effect.
If we use the local variable multiple times in for loop and foreach loop, see what happens.
The game is reversed, that means that if we have to access the local variable value multiple times in the for loop, in that case the performance will decrease.
a- This for-each loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array.
b- The for-loop is faster than the foreach-loop if the array must only be accessed once per iteration.