|
using System; |
|
using System.Collections; |
|
using System.Collections.Concurrent; |
|
using System.Collections.Generic; |
|
using System.Collections.Immutable; |
|
using System.Collections.ObjectModel; |
|
using BenchmarkDotNet.Attributes; |
|
using BenchmarkDotNet.Engines; |
|
using BenchmarkDotNet.Jobs; |
|
using BenchmarkDotNet.Running; |
|
|
|
namespace Bench_Dictionaries |
|
{ |
|
// See https://stackoverflow.com/questions/16612936/immutable-dictionary-vs-dictionary-vs-c5 |
|
// for original source of these benchmarks. |
|
|
|
class Program |
|
{ |
|
static void Main(string[] args) |
|
{ |
|
BenchmarkRunner.Run<Bench>(); |
|
} |
|
} |
|
|
|
[SimpleJob(RuntimeMoniker.Net60)] |
|
[SimpleJob(RuntimeMoniker.NetCoreApp31)] |
|
public class Bench |
|
{ |
|
private const int RandSeed = 826528; |
|
private const int BenchmarkAccessCount = 1000; |
|
|
|
[Params(100, 1000, 10000, 100000)] |
|
public int MaxItems { get; set; } |
|
|
|
private ReadOnlyDictionary<string, object> _dictionary = null!; |
|
private ReadOnlyDictionary<string, object> _concurrentDictionary = null!; |
|
private ImmutableDictionary<string, object> _immutableDictionary = null!; |
|
private string[] _randomKeys = null!; |
|
|
|
|
|
[GlobalSetup] |
|
public void GlobalSetup() |
|
{ |
|
var keyValuePairs = Enumerable.Range(0, MaxItems) |
|
.Select(i => new KeyValuePair<string, object>(i.ToString(), i)) |
|
.ToList(); |
|
|
|
// Init Dictionaries |
|
_immutableDictionary = keyValuePairs.ToImmutableDictionary(); |
|
|
|
// ImmutableDictionary.CreateRange<string, object>(); |
|
|
|
_dictionary = new ReadOnlyDictionary<string, object>( |
|
new Dictionary<string, object>(keyValuePairs)); |
|
|
|
_concurrentDictionary = new ReadOnlyDictionary<string, object>( |
|
new ConcurrentDictionary<string, object>(keyValuePairs)); |
|
|
|
// Init keys to access in benchmarks |
|
var r = new Random(RandSeed); |
|
_randomKeys = Enumerable.Range(0, BenchmarkAccessCount) |
|
.Select(i => r.Next(MaxItems).ToString()) |
|
.ToArray(); |
|
} |
|
|
|
[Benchmark] |
|
public void BaseDictionary() |
|
{ |
|
foreach (var key in _randomKeys) { |
|
_dictionary.TryGetValue(key, out var value); |
|
} |
|
} |
|
|
|
[Benchmark] |
|
public void ConcurrentDictionary() |
|
{ |
|
foreach (var key in _randomKeys) { |
|
_concurrentDictionary.TryGetValue(key, out var value); |
|
} |
|
} |
|
|
|
[Benchmark] |
|
public void ImmutableDictionaryT() |
|
{ |
|
foreach (var key in _randomKeys) { |
|
_immutableDictionary.TryGetValue(key, out var value); |
|
} |
|
} |
|
|
|
} |
|
} |