Last active
March 15, 2023 04:43
-
-
Save teoadal/01d6e0fd77a774676f533937e14cef3a 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 DictionaryEnumerationBenchmark | |
{ | |
[Benchmark(Baseline = true)] | |
public int DictionaryEnumeration() | |
{ | |
var sum = 0; | |
foreach (var entry in _dictionary) | |
{ | |
sum += entry.Value; | |
} | |
return sum; | |
} | |
[Benchmark] | |
public int GlossaryEnumeration() | |
{ | |
var sum = 0; | |
foreach (ref readonly var element in _glossary) | |
{ | |
sum += element.Key; | |
} | |
return sum; | |
} | |
#region Configuration | |
private Dictionary<int, int> _dictionary = null!; | |
private Glossary<int> _glossary; | |
[GlobalSetup] | |
public void Init() | |
{ | |
const int count = 1021; | |
_dictionary = new Dictionary<int, int>(count); | |
_glossary = new Glossary<int>(count); | |
var numbers = Enumerable.Range(0, count).ToArray(); | |
Shuffle(numbers, new Random(1234)); | |
for (var i = 0; i < count; i++) | |
{ | |
var number = numbers[i]; | |
_dictionary.Add(number, number); | |
_glossary.Add(number, number); | |
} | |
} | |
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