Last active
March 15, 2023 04:02
-
-
Save teoadal/dfc6e9d220b1dcf150418e8720af5503 to your computer and use it in GitHub Desktop.
This file contains 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.Jobs; | |
namespace Storage.Benchmark.Glo; | |
[SimpleJob(RuntimeMoniker.Net60)] | |
[SimpleJob(RuntimeMoniker.NetCoreApp31)] | |
[SimpleJob(RuntimeMoniker.Net48)] | |
[MeanColumn] | |
public class DictionaryGetValueBenchmark | |
{ | |
[Benchmark(Baseline = true)] | |
public int DictionaryGetValue() | |
{ | |
var dictionary = _dictionary; | |
var sum = 0; | |
foreach (var key in _keys) | |
{ | |
sum += dictionary[key]; | |
} | |
return sum; | |
} | |
[Benchmark] | |
public int DictionaryTryGetValue() | |
{ | |
var dictionary = _dictionary; | |
var sum = 0; | |
foreach (var key in _keys) | |
{ | |
if (dictionary.TryGetValue(key, out var value)) | |
{ | |
sum += value; | |
} | |
} | |
return sum; | |
} | |
[Benchmark] | |
public int GlossaryGetValue() | |
{ | |
var glossary = _glossary; | |
var sum = 0; | |
foreach (var key in _keys) | |
{ | |
sum += glossary.GetValue(key); | |
} | |
return sum; | |
} | |
[Benchmark] | |
public int GlossaryTryGetValue() | |
{ | |
var glossary = _glossary; | |
var sum = 0; | |
foreach (var key in _keys) | |
{ | |
if (glossary.TryGetValue(key, out var value)) | |
{ | |
sum += value; | |
} | |
} | |
return sum; | |
} | |
#region Configuration | |
private Dictionary<int, int> _dictionary = null!; | |
private Glossary<int> _glossary; | |
private int[] _keys = null!; | |
[GlobalSetup] | |
public void Init() | |
{ | |
const int count = 1021; | |
_dictionary = new Dictionary<int, int>(count); | |
_glossary = new Glossary<int>(count); | |
_keys = Enumerable.Range(0, count).ToArray(); | |
for (var i = 0; i < count; i++) | |
{ | |
var number = _keys[i]; | |
_dictionary.Add(number, number); | |
_glossary.Add(number, number); | |
} | |
Shuffle(_keys, new Random(1234)); | |
} | |
private static void Shuffle<T>(T[] array, Random random) | |
{ | |
var n = array.Length; | |
while (n > 1) | |
{ | |
var k = random.Next(n--); | |
(array[n], array[k]) = (array[k], array[n]); | |
} | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment