Created
August 29, 2025 14:30
-
-
Save FreakyAli/fcc770bb4c8a0b64150c8ed1805e8680 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.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