Skip to content

Instantly share code, notes, and snippets.

@taddison
Last active February 21, 2022 15:52
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 taddison/90d07edf9a677eeba0173b22243b4b94 to your computer and use it in GitHub Desktop.
Save taddison/90d07edf9a677eeba0173b22243b4b94 to your computer and use it in GitHub Desktop.
Dictionary TryGetValue Benchmark
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net7.0;net6.0;net5.0;netcoreapp3.1;net48;netcoreapp2.1</TargetFrameworks>
<LangVersion>7.3</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.1" />
</ItemGroup>
</Project>
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public class Program
{
public static void Main(string[] args) =>
BenchmarkSwitcher.FromAssemblies(new[] { typeof(Program).Assembly }).Run(args);
}
public class DictionaryBenchmark
{
private static readonly Dictionary<string, int> _dictionary = new Dictionary<string, int>();
private const string KEY_STRING = "abcdefghijklmnopqrstuvwxyz";
private const int MAX_KEY_LENGTH = 200;
private const int KEY_LENGTH_INCREMENT = 25;
[GlobalSetup]
public void Setup()
{
foreach (var key in GetKeyValues())
{
_dictionary.Add((string)key, 1);
}
}
[Benchmark]
[ArgumentsSource(nameof(GetKeyValues))]
public int TryGetValue(string key) => _dictionary.TryGetValue(key, out var value) ? value : default;
// https://benchmarkdotnet.org/articles/features/parameterization.html#sample-introargumentssource
public IEnumerable<object> GetKeyValues()
{
var keyString = KEY_STRING;
while(keyString.Length < MAX_KEY_LENGTH)
{
keyString += KEY_STRING;
}
for (int i = 1; i <= keyString.Length; i += KEY_LENGTH_INCREMENT)
{
yield return keyString.Substring(0, i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment