Last active
September 28, 2023 09:18
-
-
Save sonnemaf/b91e7edc5531982b70a1e65235cba40f to your computer and use it in GitHub Desktop.
ToList(capacity) Benchmark
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 BenchmarkDotNet.Running; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Jobs; | |
BenchmarkRunner.Run<BM>(); | |
[SimpleJob(RuntimeMoniker.Net80, baseline: true)] | |
[SimpleJob(RuntimeMoniker.Net70)] | |
[SimpleJob(RuntimeMoniker.Net48)] | |
[MemoryDiagnoser(displayGenColumns: false)] | |
[HideColumns("Job", "Error", "StdDev", "Median", "RatioSD", "Alloc Ratio")] | |
public class BM { | |
[Benchmark] | |
public int[] ToArray() => | |
GetData().Where(static n => n % 4 == 0).ToArray(); | |
[Benchmark] | |
public List<int> ToList() => | |
GetData().Where(static n => n % 4 == 0).ToList(); | |
[Benchmark] | |
public List<int> ToListWithCapacity() => | |
GetData().Where(static n => n % 4 == 0).ToList(capacity: 25_000); | |
private IEnumerable<int> GetData() { | |
for (int i = 0; i < 100_000; i++) { | |
yield return i; | |
} | |
} | |
} | |
public static class Extensions { | |
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source, int capacity) { | |
if (source is null) { | |
throw new ArgumentNullException(nameof(source)); | |
} | |
if (capacity < 0) { | |
throw new ArgumentOutOfRangeException(nameof(capacity), "Non-negative number required."); | |
} | |
var list = new List<TSource>(capacity); | |
list.AddRange(source); | |
return list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
| Method | Runtime | Mean | Ratio | Allocated |
|------------------- |------------------- |---------:|------:|----------:|-
| ToArray | .NET 7.0 | 653.0 μs | 2.66 | 226.41 KB |
| ToArray | .NET 8.0 | 244.9 μs | 1.00 | 226.41 KB |
| ToArray | .NET Framework 4.8 | 699.6 μs | 2.86 | 354.47 KB |
| | | | | |
| ToList | .NET 7.0 | 648.9 μs | 2.62 | 256.44 KB |
| ToList | .NET 8.0 | 247.9 μs | 1.00 | 256.44 KB |
| ToList | .NET Framework 4.8 | 692.2 μs | 2.80 | 256.88 KB |
| | | | | |
| ToListWithCapacity | .NET 7.0 | 730.3 μs | 3.05 | 97.81 KB |
| ToListWithCapacity | .NET 8.0 | 239.2 μs | 1.00 | 97.81 KB |
| ToListWithCapacity | .NET Framework 4.8 | 719.1 μs | 3.01 | 97.93 KB |