Skip to content

Instantly share code, notes, and snippets.

@danield137
Last active November 24, 2019 09:18
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 danield137/57d4b16b23f409e1198c4690e36b5fd5 to your computer and use it in GitHub Desktop.
Save danield137/57d4b16b23f409e1198c4690e36b5fd5 to your computer and use it in GitHub Desktop.
Benchmark ToList vs IEnumerable
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
namespace DanielDoesBenchmarks
{
[SimpleJob(RuntimeMoniker.Net472, baseline: true)]
public class ListBenchmarks
{
[Params(100, 100000, 10000000)]
public int N; // Give it a reasonable default
private List<int> lst; // This is what we'll check
private IEnumerable<int> result;
[GlobalSetup]
public void Setup()
{
lst = new List<int>();
for (int i = 0; i < N; i++)
{
lst.Add(i);
}
result = lst.Where(i => i % 5 == 0);
}
[Benchmark]
public void ToList()
{
var again = this.result.ToList();
var counter = 0;
foreach (var i in again)
{
counter++;
}
foreach (var i in again)
{
counter++;
}
}
[Benchmark]
public void IEnunerable()
{
var counter = 0;
foreach (var i in result)
{
counter++;
}
foreach (var i in result)
{
counter++;
}
}
}
}
using System;
using BenchmarkDotNet.Running;
namespace DanielDoesBenchmarks
{
public class Program
{
public static void Main()
{
var summary = BenchmarkRunner.Run<ListBenchmarks>();
Console.ReadLine();
}
}
}
@danield137
Copy link
Author

// * Summary *

BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18362
Intel Core i7-8650U CPU 1.90GHz (Kaby Lake R), 1 CPU, 8 logical and 4 physical cores
[Host] : .NET Framework 4.8 (4.8.4042.0), X86 LegacyJIT
Job-SWSWQT : .NET Framework 4.8 (4.8.4042.0), X86 LegacyJIT

Runtime=.NET 4.7.2

Method N Mean Error StdDev Median Ratio
ToList 100 1.837 us 0.1527 us 0.4307 us 1.689 us 1.00
IEnunerable 100 1.814 us 0.1062 us 0.2960 us 1.663 us 1.00
ToList 100000 1,122.106 us 21.5508 us 21.1658 us 1,124.358 us 1.00
IEnunerable 100000 1,618.578 us 38.2310 us 40.9067 us 1,609.631 us 1.00
ToList 10000000 110,225.596 us 2,198.9050 us 4,441.8966 us 110,100.870 us 1.00
IEnunerable 10000000 153,495.925 us 3,054.8255 us 6,575.8341 us 150,926.413 us 1.00

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment