
The following code takes a long time to run. In fact, I’m writing this blog post while this is running, and I’m not sure how long that will take.
unsafe class Program
{
public class NumericValue
{
public string Name;
public object Value;
public override bool Equals(object obj)
{
return obj is NumericValue value &&
Name == value.Name &&
Equals(Value, value.Value);
}
public unsafe override int GetHashCode()
{
Span<byte> span;
if (Value is long l)
{
span = new Span<byte>(&l, sizeof(long));
}
else if (Value is int i)
{
span = new Span<byte>(&l, sizeof(int));
}
else
{
throw new NotSupportedException("Unknown value");
}
return (int)Standart.Hash.xxHash.xxHash32.ComputeHash(span,
span.Length, (uint)Name.GetHashCode());
}
}
static void Main(string[] args)
{
var dic = new Dictionary<NumericValue, int>();
var sp = Stopwatch.StartNew();
for (int i = 0; i < 100_000; i++)
{
dic.Add(new NumericValue
{
Name = "test",
Value = i
}, i);
}
Console.WriteLine(sp.ElapsedMilliseconds);
}
}
Update: This took over a minute to complete on my machine (which is pretty nice).
The killer is that this code is correct, it does the right thing, but it can be slow. I stripped a much larger scenario to ~50 lines of code, can you see what is going on? And why?
Woah, already finished? 🤯
If you found the article interesting, don’t miss a chance to try our database solution – totally for free!

