C# Performance Of Code - For Loop VS Foreach Loop

Introduction

I had a small experiment to prove the point under discussion. I have a table named accounts in SQL Server database and I added 20,000 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. The foreach loop took 107 milliseconds to execute the same process while the classic for loop took 14 milliseconds.

Now, why does this happen? Let's go a bit deeper.

For Loop Vs. Foreach Loop

The for loop version uses enough stack space for only two local variables (counter and i). The Foreach version, on the other hand, 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 the for loop and foreach loop, see what happens.

The game is reversed. If we have to access the local variable value multiple times in the for loop, in that case, the performance will decrease.

Summary

  • This foreach 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.
  • The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


Similar Articles