Skip to content

Instantly share code, notes, and snippets.

@Horusiath
Last active May 14, 2018 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Horusiath/2c4aefb8b4b2c36bfc2c1fcea4f2d5e2 to your computer and use it in GitHub Desktop.
Save Horusiath/2c4aefb8b4b2c36bfc2c1fcea4f2d5e2 to your computer and use it in GitHub Desktop.
Direct vs indirect enumerator call
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
namespace Benchmarks
{
public class EnumeratorBenchmarks
{
private const int SIZE = 1_000_000;
private static readonly int[] array = GetArray();
private static readonly IEnumerable<int> enumerable = GetArray();
public static int[] GetArray()
{
var a = new int[SIZE];
for (int i = 0; i < SIZE; i++)
{
a[i] = i;
}
return a;
}
[Benchmark]
public int Array_sum()
{
var sum = 0;
foreach (var i in array)
{
sum += i;
}
return sum;
}
[Benchmark]
public int Enumerable_sum()
{
var sum = 0;
foreach (var i in enumerable)
{
sum += i;
}
return sum;
}
}
}
BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=2.1.300-rc1-008673
  [Host]     : .NET Core 2.0.7 (CoreCLR 4.6.26328.01, CoreFX 4.6.26403.03), 64bit RyuJIT
  DefaultJob : .NET Core 2.0.7 (CoreCLR 4.6.26328.01, CoreFX 4.6.26403.03), 64bit RyuJIT
Method Mean Error StdDev
Array_sum 632.2 us 15.60 us 23.82 us
Enumerable_sum 6,147.8 us 122.89 us 131.50 us
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment