Posts · 8 November 2026 · 5 min read · 46 reads

My Struct Key Was Boxed Two Million Times

A small struct with three int fields silently produced boxing during Dictionary lookups. The cause of the problem and a two-line fix.

I had a cache that worked with a small struct made of three integers. It was designed as a value type and was a plain data carrier. During a batch job, roughly two million lookups were made in a Dictionary that used this struct as its key. One day that lookup loop showed up in an allocation profile. At first glance this made no sense, because a dictionary lookup normally doesn't allocate. It computes the key's hash, walks the bucket, and compares. So where was the garbage coming from?

The answer was in the key itself. Every lookup was boxing the key, and I had not written a single new that would trigger it.

Who compares dictionary keys

When you put an entry into a Dictionary<TKey, TValue>, the dictionary needs two things from the key: a hash code, and a way to tell two keys apart. It gets both through EqualityComparer<TKey>.Default. Which comparer gets selected depends on your type. I had never thought about this, so in the sample code I printed the comparer that was chosen.

Console.WriteLine(EqualityComparer<PlainKey>.Default.GetType().Name);
Console.WriteLine(EqualityComparer<FastKey>.Default.GetType().Name);

Both structs had the same three fields, but they ended up with different comparers. The only difference was that one of them implemented the IEquatable<T> interface.

A struct that implements the interface goes to the GenericEqualityComparer<T> path. This comparer calls the Equals(T) method you wrote directly and takes the struct as a value. There is no boxing and no reflection.

A struct that doesn't implement the interface works with ObjectEqualityComparer<T>. This comparer only knows the two methods every object has: GetHashCode and Equals(object). These methods are defined on object, so to reach the struct the runtime has to box it first. Since I had not written those methods, the versions being called were the ValueType defaults, which compare the fields through reflection at runtime. That meant every lookup boxed the key once to get the hash and once more for the equality check.

The bill

When I compared the same struct with and without the methods written, the table looked like this. The two million lookups ran against a dictionary with two hundred thousand entries. The keys were generated up front, so only the lookup cost was measured. Each measurement was taken as the best of five runs. The ratio caught my attention more than the milliseconds:

PlainKey (default equality)    192,000,040 bytes    695.8 ms
FastKey (IEquatable<T>)               40 bytes      236.5 ms

The lookups, which should not allocate at all, had produced 192 megabytes of boxes. That came to about ninety-six bytes of garbage per lookup. A few short-lived boxes were created each time, all piling up in the gen0 heap and left for the garbage collector later. In terms of time it was also about three times slower, because reflection-based equality is expensive even apart from the allocations. The checksums were identical in both versions. So both codes had found the same records and done the same work. Only one of them was doing it while wasting resources.

The fix: three methods or one keyword

The fix is a mechanical operation:

struct FastKey(int x, int y, int z) : IEquatable<FastKey>
{
    public readonly int X = x, Y = y, Z = z;
    public bool Equals(FastKey other) => X == other.X && Y == other.Y && Z == other.Z;
    public override bool Equals(object? obj) => obj is FastKey o && Equals(o);
    public override int GetHashCode() => HashCode.Combine(X, Y, Z);
}

The key to switching to the fast comparer is the IEquatable<FastKey>.Equals method. The object.Equals override keeps the two equality implementations consistent with each other. And HashCode.Combine saves you from the trouble of writing a hand-rolled hash that might distribute poorly.

Or you can skip all of that and let the compiler write it for you: a record struct FastKey(int X, int Y, int Z) declaration generates IEquatable<T>, both Equals methods, and GetHashCode. Today I prefer this route. If a value type might end up as a dictionary key, a HashSet element, or an input to Distinct or Contains in LINQ, I make it a record struct from the start and don't think about the issue again.

When it doesn't matter

If you never use the struct as a key and never compare two of its instances with each other, this problem never comes into play. In that case adding the methods is just noise for the next person who reads the file. A struct that only carries data from one place to another doesn't need an equality contract.

The real trap is the silent upgrade. A value type that works fine as a bag of fields keeps working fine until someone puts it into a dictionary. The compiler gives no warning, the code compiles, and the lookups return the right results. The only trace is a line in a memory graph that nobody is looking at.

The fix also has a limit. If you write GetHashCode by hand, keep the fields that will change away from the struct while it sits in a hash-based collection. A key whose hash changes after it has been stored is a different and much harder bug to find. The structs I use as keys have all their fields marked readonly, and the sample code does the same.

I would have preferred to put the runnable sample code on GitHub, but this time the environment could not push to my sample repository. So I'm leaving the full code below. You can paste it into a net10.0 console project and run it with dotnet run -c Release.

So do you make your small value types record struct by default, or do you wait until the equality problem shows up?

Read the original article on DEV Community ↗

Comments (0)

No comments yet; be the first.

Leave a comment

Comments are published after approval.