Member-only story
Performance of the Loops … in C#
As strange as one might think, the topic of the performance of loops in C# is not that trivial. I am talking here about high performance applications where every millisecond counts.
Looping over an Array
Consider an array of 100 millions integers, that you want to scan as fast as you can. What would be the right way to do it ?
C# provides several ways to loop over an array or a collection:
- for, while
- foreach
- Array.ForEach()
- Enumerator
The tests were done using .Net 4.5 and .Net 4.6 frameworks on x64 Core i7 machine.
The “for” and the “while” unsurprisingly have similar performance; both score 55ms execution time.
However the “foreach” behavior is nothing less than weird. When it is run for the first time on an uninitialized array, it takes 120ms. If called a second time the performance beats the one of “for” and makes it in 45ms.
A quick look at the IL code generated by the compiler, you find that the IL of “foreach” is very similar to “for”. Actually the compiler recognizes that the collection is an array and generates an IL code similar to the “for”.

However there is “apparently” nothing in the IL code nor in the machine code emitted by the JIT that explains the difference in performance between the first and second call to “foreach”.
To make things weirder, if you partially initialize the array by filling some percentage of the elements with arbitrary values, the first “foreach” call starts to show some performance gain proportional to the initialization percentage.
Here’s what I mean:
- 0% of the array is initialized, the first call to “foreach” takes 120ms
- 25% of the array is initialized, the first call to “foreach” takes 100ms
- 50% of the array is initialized, the first call to “foreach” takes 80ms
- 75% of the array is initialized, the first call to “foreach” takes 60ms
- 100% of the array is initialized, the first call to “foreach” takes 45ms