Skip to content

Instantly share code, notes, and snippets.

@AlexMerzlikin
Last active January 16, 2022 08:12
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 AlexMerzlikin/faed898d499ff6c95e3daedbb6debb6d to your computer and use it in GitHub Desktop.
Save AlexMerzlikin/faed898d499ff6c95e3daedbb6debb6d to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
namespace ArrayVsDictionaryLookup
{
[MemoryDiagnoser]
public class LookupBenchmarks
{
[Params(5, 10, 15, 20, 25, 30, 40, 50)]
public int Size;
private int[] _array;
private Dictionary<int, int> _dictionary;
private int[] _valuesToLookUp;
private readonly int _valuesToLookUpSize = 10;
private readonly Random _random = new Random(42);
[GlobalSetup]
public void GlobalSetup()
{
_valuesToLookUp = Enumerable
.Repeat(0, _valuesToLookUpSize)
.Select(i => _random.Next(0, Size))
.ToArray();
_array = new int[Size];
_dictionary = new Dictionary<int, int>(Size);
for (var i = 0; i < _array.Length; i++)
{
_array[i] = i;
_dictionary[i] = i;
}
}
[Benchmark]
public void ArrayLookupLinearSearch()
{
foreach (var value in _valuesToLookUp)
{
var result = Find(value);
}
}
[Benchmark]
public void ArrayLookupBinarySearch()
{
foreach (var value in _valuesToLookUp)
{
var result = BinarySearch(_array, 0, _array.Length, value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int Find(int key)
{
var length = _array.Length;
for (var i = 0; i < length; i++)
{
if (_array[i] == key)
{
return _array[i];
}
}
return 0;
}
[Benchmark]
public void DictionaryLookup()
{
foreach (var value in _valuesToLookUp)
{
_dictionary.TryGetValue(value, out var result);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int BinarySearch(int[] arr,
int left,
int right,
int value)
{
while (true)
{
if (right < left)
{
return -1;
}
var mid = left + (right - left) / 2;
if (arr[mid] == value)
{
return arr[mid];
}
if (arr[mid] > value)
{
right = mid - 1;
continue;
}
left = mid + 1;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment