Performance of the Loops … in C#

Ziad SALLOUM
4 min readJun 4, 2017

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”.

Similarity between “for” and “foreach” when looping over an array of integers

--

--

No responses yet