Skip to content

Instantly share code, notes, and snippets.

@itn3000
Created June 2, 2022 02:44
Show Gist options
  • Save itn3000/613d2fd76fd9d60df6a8a7a0d47e53fc to your computer and use it in GitHub Desktop.
Save itn3000/613d2fd76fd9d60df6a8a7a0d47e53fc to your computer and use it in GitHub Desktop.
ConcurrentDictionary.TryGetValue comparison by key types.
// This benchmark use one record and TryGetValue returns true.
// Results will be affected by record num and whether match any record or not.
using System.Collections.Concurrent;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<ConcurrentDictionaryBench>();
record C1(string a, int b, string c);
record struct S2(string a, int b);
record C2(string a, int b);
[MemoryDiagnoser]
// [ShortRunJob]
public class ConcurrentDictionaryBench
{
private static readonly ConcurrentDictionary<(string, int), C1> dic1 = new();
private static readonly ConcurrentDictionary<string, C1> dic2 = new();
private static readonly ConcurrentDictionary<Tuple<string, int>, C1> dic3 = new();
private static readonly ConcurrentDictionary<S2, C1> dic4 = new();
private static readonly ConcurrentDictionary<C2, C1> dic5 = new();
private static readonly C1 _instance = new C1("hoge", 1, "piyo");
[GlobalSetup]
public void Setup()
{
dic1[(_instance.a, _instance.b)] = _instance;
dic2[$"{_instance.a}_{_instance.b}"] = _instance;
dic3[Tuple.Create(_instance.a, _instance.b)] = _instance;
dic4[new S2(_instance.a, _instance.b)] = _instance;
dic5[new C2(_instance.a, _instance.b)] = _instance;
}
[Benchmark]
public void VTuple()
{
dic1.TryGetValue((_instance.a, _instance.b), out var val);
}
[Benchmark]
public void CombinedString()
{
dic2.TryGetValue($"{_instance.a}_{_instance.b}", out var val);
}
[Benchmark]
public void ClassTuple()
{
dic3.TryGetValue(Tuple.Create(_instance.a, _instance.b), out var val);
}
[Benchmark]
public void RecordStruct()
{
dic4.TryGetValue(new S2(_instance.a, _instance.b), out var val);
}
[Benchmark]
public void RecordClass()
{
dic5.TryGetValue(new C2(_instance.a, _instance.b), out var val);
}
}
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19044.1706 (21H2)
Intel Core i7-9700 CPU 3.00GHz, 1 CPU, 8 logical and 8 physical cores
.NET SDK=6.0.300
  [Host]     : .NET 6.0.5 (6.0.522.21309), X64 RyuJIT
  DefaultJob : .NET 6.0.5 (6.0.522.21309), X64 RyuJIT

Method Mean Error StdDev Gen 0 Allocated
VTuple 31.19 ns 0.301 ns 0.282 ns - -
CombinedString 58.22 ns 0.510 ns 0.477 ns 0.0063 40 B
ClassTuple 74.28 ns 1.434 ns 1.271 ns 0.0166 104 B
RecordStruct 17.18 ns 0.069 ns 0.061 ns - -
RecordClass 35.05 ns 0.233 ns 0.207 ns 0.0051 32 B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment