Skip to content

Instantly share code, notes, and snippets.

@mgravell
Last active October 23, 2024 10:02
Show Gist options
  • Save mgravell/f6082624290d14f44068a42e20a9b7db to your computer and use it in GitHub Desktop.
Save mgravell/f6082624290d14f44068a42e20a9b7db to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Buffers;
using System.Security.Cryptography;
using System.Text;
BenchmarkRunner.Run<HashBench>();
[MemoryDiagnoser]
public class HashBench
{
[Params(10, 100, 800)]
public int Size
{
get => Key.Length;
set
{
if (Size != value)
{
var rand = new Random(12345);
char[] chars = ArrayPool<char>.Shared.Rent(value);
for(int i = 0; i < value; i++)
{
chars[i] = (char)rand.Next(32, 128);
}
Key = new string(chars, 0, value);
ArrayPool<char>.Shared.Return(chars);
}
}
}
public static readonly StringComparer Comparer = StringComparer.Ordinal;
public string Key { get; set; } = "";
[Benchmark(Baseline = true)]
public void DirectOrdinal()
{
var key = Key;
_ = Comparer.GetHashCode(key);
_ = Comparer.Equals(key, key);
}
[Benchmark]
public void DirectNatural()
{
var key = Key;
_ = key.GetHashCode();
_ = key.Equals(key);
}
[Benchmark]
public void ViaHashedKey()
{
var hashed = GetHashedCacheKey(Key);
_ = hashed.GetHashCode();
_ = hashed.Equals(hashed);
}
private static string GetHashedCacheKey(string key)
{
using var md5 = MD5.Create();
var inputAsBytes = Encoding.UTF8.GetBytes(key);
var hashBytes = md5.ComputeHash(inputAsBytes);
var sb = new StringBuilder();
foreach (var byt in hashBytes)
{
sb.Append(byt.ToString("X2"));
}
return sb.ToString();
}
}
Method Size Mean Error StdDev Ratio RatioSD Gen0 Allocated Alloc Ratio
DirectOrdinal 10 4.339 ns 0.0131 ns 0.0116 ns 1.00 0.00 - - NA
DirectNatural 10 4.454 ns 0.0141 ns 0.0132 ns 1.03 0.00 - - NA
ViaHashedKey 10 495.167 ns 9.1316 ns 8.5417 ns 114.13 1.93 0.0629 1056 B NA
DirectOrdinal 100 45.495 ns 0.4241 ns 0.3967 ns 1.00 0.01 - - NA
DirectNatural 100 44.201 ns 0.1409 ns 0.1177 ns 0.97 0.01 - - NA
ViaHashedKey 100 573.756 ns 6.8082 ns 6.3684 ns 12.61 0.17 0.0677 1144 B NA
DirectOrdinal 800 363.484 ns 2.3475 ns 2.0810 ns 1.00 0.01 - - NA
DirectNatural 800 361.123 ns 0.9744 ns 0.9114 ns 0.99 0.01 - - NA
ViaHashedKey 800 1,479.989 ns 4.5036 ns 4.2126 ns 4.07 0.03 0.1087 1840 B NA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment