Search code examples
c#loopsclr

What is CLR loop optimization behavior?


I was wondering that if I iterate over an array with foreach the JITter later will replace the foreach loop with simple for-loop to drop enumerator penalty, is this true? and if it is, what about List? because list is backed with an array.

And finally what is the optimizations on Linq, consider following:

var result = typeof(List<int>).GetInterfaces()
    .FirstOrDefault(i => i.IsGenericType);

Will this get any optimizations?


Solution

  • On C# 2.8.2 (it should be the latest as 25 July 2018) on .NET 4.7.2650:

    • the for and foreach on an array are fully optimized, and

    • the for on a List<T> is fully optimized by inlining the code of .Count and the indexer [].

    You can see it on sharplab, right pane: the methods ArrayFor, ArrayForEach and ListFor don't call external methods (but ListFor has the code to call the ThrowArgumentOutOfRangeException method, that is the call made by the indexer []). ListForEach has calls to System.Collections.Generic.List``1+Enumerator[[System.Int32, mscorlib]].MoveNext() so it isn't wholly inlined. EnumerableForEach doesn't have explicit calls where you can see method names because by using an interface it can use directy the addresses of the methods (see the various call dword [0x218a0084], call dword [0x218a0088]...)