Array iteration performance in C#

Implementing the sum of the items in an array is very simple. I think most developers would implement it this way:

static int Sum(int[] array)
{
    var sum = 0;
    for (var index=0; index<array.Length; index++)
        sum += array[index];
    return sum;
}

There’s actually a simpler alternative in C#:

static int Sum(int[] array)
{
    var sum = 0;
    foreach (var item in array)
        sum += item;
    return sum;
}

Another alternative is to use the Sum() operation provided by LINQ. It can be applied to any enumerable, including arrays.


So, how do these fair in terms of performance?


You can see that, comparing to using a for loop, using a foreach loop is almost 1.4 times faster, while using LINQ is almost 7 times slower and allocates on the heap. Why is that?

NOTE: All benchmarks were performed on .NET 6.0 Preview 5. The results may vary on other target frameworks.


LINQ


If you check the source code for the Sum() in System.Linq, you’ll find that it uses a foreach loop. So, if using a foreach is faster than a for, why is it so slow in this case?


Notice that Sum() is an extension method for the type IEnumerable<int>. Unlike