Skip to content

Instantly share code, notes, and snippets.

@FreakyAli
Created August 29, 2025 14:30
Show Gist options
  • Save FreakyAli/fcc770bb4c8a0b64150c8ed1805e8680 to your computer and use it in GitHub Desktop.
Save FreakyAli/fcc770bb4c8a0b64150c8ed1805e8680 to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Engines;
[MemoryDiagnoser]
public class DictionaryIterationBenchmark
{
private Dictionary<string, int> dict = null!;
[Params(10, 1_000, 100_000)]
public int Size;
private readonly Consumer consumer = new Consumer();
[GlobalSetup]
public void Setup()
{
dict = new Dictionary<string, int>(Size);
for (int i = 0; i < Size; i++)
{
dict[$"Key{i}"] = i;
}
}
[Benchmark(Baseline = true)]
public void IterateWithKeyValuePair()
{
foreach (var kvp in dict)
{
// Do some real work so JIT can’t optimize away
consumer.Consume($"{kvp.Key}:{kvp.Value}");
}
}
[Benchmark]
public void IterateWithDeconstruction()
{
foreach (var (fruit, count) in dict)
{
consumer.Consume($"{fruit}:{count}");
}
}
}
public class Program
{
public static void Main(string[] args)
{
BenchmarkRunner.Run<DictionaryIterationBenchmark>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment