Skip to content

Instantly share code, notes, and snippets.

@davepcallan
Created November 30, 2024 15:50
Show Gist options
  • Save davepcallan/7404977d4c68e9b8761522ed67ccad7c to your computer and use it in GitHub Desktop.
Save davepcallan/7404977d4c68e9b8761522ed67ccad7c to your computer and use it in GitHub Desktop.
.NET 9 new LINQ CountBy compared to existing approaches benchmarks
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