-
-
Save sonnemaf/b91e7edc5531982b70a1e65235cba40f to your computer and use it in GitHub Desktop.
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; | |
} | |
} |
BenchmarkDotNet v0.13.8, Windows 11 (10.0.22621.2361/22H2/2022Update/SunValley2)
AMD Ryzen 9 3900X, 1 CPU, 24 logical and 12 physical cores
.NET SDK 8.0.100-rc.1.23455.8
[Host] : .NET 8.0.0 (8.0.23.41904), X64 RyuJIT AVX2
.NET 7.0 : .NET 7.0.11 (7.0.1123.42427), X64 RyuJIT AVX2
.NET 8.0 : .NET 8.0.0 (8.0.23.41904), X64 RyuJIT AVX2
.NET Framework 4.8 : .NET Framework 4.8.1 (4.8.9181.0), X64 RyuJIT VectorSize=256
| 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 |
| Method | Runtime | Mean | Ratio | Allocated |
|------------------- |--------- |---------:|------:|----------:|-
| ToArray | .NET 7.0 | 599.9 μs | 2.50 | 206.87 KB |
| ToArray | .NET 8.0 | 240.1 μs | 1.00 | 206.87 KB |
| | | | | |
| ToList | .NET 7.0 | 636.7 μs | 2.37 | 256.44 KB |
| ToList | .NET 8.0 | 268.1 μs | 1.00 | 256.44 KB |
| | | | | |
| ToListWithCapacity | .NET 7.0 | 698.0 μs | 2.82 | 78.27 KB |
| ToListWithCapacity | .NET 8.0 | 247.1 μs | 1.00 | 78.27 KB |