Created
November 30, 2024 15:50
-
-
Save davepcallan/7404977d4c68e9b8761522ed67ccad7c to your computer and use it in GitHub Desktop.
.NET 9 new LINQ CountBy compared to existing approaches benchmarks
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.Attributes; | |
using BenchmarkDotNet.Columns; | |
using BenchmarkDotNet.Configs; | |
using BenchmarkDotNet.Environments; | |
using BenchmarkDotNet.Jobs; | |
using BenchmarkDotNet.Reports; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Benchmarks | |
{ | |
[Config(typeof(Config))] | |
[HideColumns(Column.Job, Column.RatioSD, Column.AllocRatio)] | |
[MemoryDiagnoser] | |
[ReturnValueValidator(true)] | |
public class CountByDotnet9 | |
{ | |
private static int SequenceLength = 100000; | |
private static int GroupsCount = 100; | |
private static Random random = new(42); | |
private static readonly int[] Seq = Enumerable | |
.Range(0, SequenceLength) | |
.Select(_ => random.Next(0, GroupsCount)).ToArray(); | |
[Benchmark] | |
public IDictionary<int, int> Grouping() => | |
Seq | |
.GroupBy(x => x) | |
.ToDictionary(x => x.Key, x => x.Count()); | |
[Benchmark] | |
public IDictionary<int, int> LookupDict() => | |
Seq | |
.ToLookup(x => x) | |
.ToDictionary(x => x.Key, x => x.Count()); | |
[Benchmark(Baseline = true)] | |
public IDictionary<int, int> Counting() => | |
Seq | |
.CountBy(x => x) | |
.ToDictionary(x => x.Key, x => x.Value); | |
private class Config : ManualConfig | |
{ | |
public Config() | |
{ | |
AddJob(Job.Default.WithId(".NET 9").WithRuntime(CoreRuntime.Core90)); | |
SummaryStyle = | |
SummaryStyle.Default.WithRatioStyle(RatioStyle.Percentage); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment