Patrick Smacchia wrote a post where he compares execution time while using different patterns to iterate over a collection, namely List<int> and int. Since he provided the code, I decided to give it a go as well. Only thing I did, was I added [MethodImpl(MethodImplOptions.NoInlining)] for each method, since they all were very simple, and could easily be inlined.
That said, here are my results (release build ran without debugger, outside of Visual Studio):
If you compare those to Patrick’s results, you may notice few things:
- Patrick has a faster PC (which only reminds me I really should start looking for a new one)
- When you turn off inlining results are much different. First, foreach is as efficient on arrays as on lists (which is different than Patrick’s results. My guess is, that since CLR has more intimate knowledge of arrays, it somehow optimized it when inlining was turned on).
- iterating with for loop is faster when you do the trick Patrick called “count optimization”. This is quite the contrary to what Eric Gunnerson said, and I’m puzzled about it.
- DO NOT all go and change your foreaching code to for loops! The numbers you see are number of ticks when iterating over a collection of 100 000 000 elements! That means that in each and every case, iteration is fast as hell, and it’s NOT your bottleneck. To help you visualize that, here’s a picture I borrowed from K. Scott Allen