Skip to content

Instantly share code, notes, and snippets.

@teoadal
Last active March 15, 2023 03:58
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 teoadal/0bf7114bf07a2e77c91bda5bc7af4a66 to your computer and use it in GitHub Desktop.
Save teoadal/0bf7114bf07a2e77c91bda5bc7af4a66 to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
namespace Storage.Benchmark.Glo;
[SimpleJob(RuntimeMoniker.Net60)]
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
[SimpleJob(RuntimeMoniker.Net48)]
[MeanColumn]
public class DictionaryGetWriteValueBenchmark
{
[Benchmark(Baseline = true)]
public int Dictionary()
{
var dictionary = _dictionary;
var sum = 0;
foreach (var key in _keys)
{
var value = dictionary[key];
sum += value;
dictionary[key] = sum;
}
return sum;
}
[Benchmark]
public int DictionaryMarshal()
{
var dictionary = _dictionary;
var sum = 0;
foreach (var key in _keys)
{
#if NET6_0
ref var value = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrNullRef(dictionary, key);
sum += value;
value = sum;
#else
var value = dictionary[key];
sum += value;
dictionary[key] = sum;
#endif
}
return sum;
}
[Benchmark]
public int Glossary()
{
var glossary = _glossary;
var sum = 0;
foreach (var key in _keys)
{
ref var value = ref glossary.GetValue(key);
sum += value;
value = sum;
}
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