Skip to content

Instantly share code, notes, and snippets.

@Ruikuan
Last active May 3, 2022 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ruikuan/ae80146eb7673f956c705f10560df103 to your computer and use it in GitHub Desktop.
Save Ruikuan/ae80146eb7673f956c705f10560df103 to your computer and use it in GitHub Desktop.
Benchmark Dictionary and ConcurrentDictionary
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Collections.Concurrent;
var summary = BenchmarkRunner.Run(typeof(Program).Assembly);
class Helper
{
public static string Repeat(string str, int count)
{
return string.Create(str.Length * count, (str, count), (span, state) =>
{
var (val, n) = state;
var span1 = span;
for (int i = 0; i < n; i++)
{
val.AsSpan().CopyTo(span1);
span1 = span1[val.Length..];
}
});
}
}
public class BenchmarkingA
{
private Dictionary<string, string> _dic = new Dictionary<string, string>();
private ConcurrentDictionary<string, string> _currentDic = new ConcurrentDictionary<string, string>();
private string? testKey;
[GlobalSetup]
public void Setup()
{
foreach (var i in Enumerable.Range(1, 100))
{
string key = Helper.Repeat("Aa", i);
_dic[key] = key;
_currentDic[key] = key;
}
testKey = Helper.Repeat("Aa", 40);
}
[Benchmark(Baseline = true)]
public string GetDic()
{
return _dic[testKey!];
}
[Benchmark]
public string GetCurrectDic()
{
return _currentDic[testKey!];
}
}

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19043.1645 (21H1/May2021Update) Intel Core i7-3720QM CPU 2.60GHz (Ivy Bridge), 1 CPU, 8 logical and 4 physical cores .NET SDK=6.0.202 [Host] : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT DefaultJob : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT

Method Mean Error StdDev Ratio
GetDic 50.36 ns 0.225 ns 0.200 ns 1.00
GetCurrectDic 94.99 ns 0.457 ns 0.405 ns 1.89

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19044.1645 (21H2) Intel Core i9-10885H CPU 2.40GHz, 1 CPU, 16 logical and 8 physical cores .NET SDK=6.0.202 [Host] : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT DefaultJob : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT

Method Mean Error StdDev Ratio RatioSD
GetDic 31.11 ns 0.238 ns 0.222 ns 1.00 0.00
GetCurrectDic 63.61 ns 0.735 ns 0.687 ns 2.04 0.02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment