Last active
November 24, 2019 09:18
-
-
Save danield137/57d4b16b23f409e1198c4690e36b5fd5 to your computer and use it in GitHub Desktop.
Benchmark ToList vs IEnumerable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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++; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using BenchmarkDotNet.Running; | |
namespace DanielDoesBenchmarks | |
{ | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var summary = BenchmarkRunner.Run<ListBenchmarks>(); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// * 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