I have a really simple benchmark to measure and compare performance of Dictionary<string, int> and ConcurrentDictionary<string, int>:
[MemoryDiagnoser]
public class ExtremelySimpleDictionaryBenchmark
{
private readonly List<string> _keys = new();
private readonly Dictionary<string, int> _dict = new ();
private readonly ConcurrentDictionary<string, int> _concurrentDict = new ();
private const int DictionarySize = 300;
private const string Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static string Generate(int length, Random random)
{
var result = new char[length];
for (var i = 0; i < length; i++)
result[i] = Alphabet[random.Next(Alphabet.Length)];
return new string(result);
}
[GlobalSetup]
public void Setup()
{
var rnd = new Random();
for (var i = 0; i < DictionarySize; i++)
{
var key = Generate(6, rnd);
var count = rnd.Next(1000);
_dict[key] = count;
_concurrentDict[key] = count;
_keys.Add(key);
}
}
[Benchmark(Baseline = true)]
public int Dictionary()
{
// variable res is used to avoid dead code elimination
var res = 0;
for (var index = 0; index < _keys.Count; index++)
if(_dict.TryGetValue(_keys[index], out var value))
res += value;
return res;
}
[Benchmark]
public int ConcurrentDictionary()
{
// variable res is used to avoid dead code elimination
var res = 0;
for (var index = 0; index < _keys.Count; index++)
if(_concurrentDict.TryGetValue(_keys[index], out var value))
res += value;
return res;
}
}
It produces a really weird results. ConcurrentDictionary.TryGetvalue beats Dictionary.TryGetvalue in terms of performance. I have the following results:
| Method | Mean | Error | StdDev | Ratio | Allocated | Alloc Ratio |
|---|---|---|---|---|---|---|
| Dictionary | 2.055 us | 0.0230 us | 0.0215 us | 1.00 | - | NA |
| ConcurrentDictionary | 1.522 us | 0.0172 us | 0.0152 us | 0.74 | - | NA |
The benchmark was ran on .NET Core 8, Windows 11. Processor is Intel Core i7-14650HX. How can such results be explained?
Dictionary<K,V>. I don't know how to contact him or whether there is a good place to post an issue about this.