Menu

My Struct Key Boxed Itself Two Million Times
📰

My Struct Key Boxed Itself Two Million Times

DEV Community: dotnet·Sukhpinder Singh·15 days ago
#4I0cP0ve
#devtodotnet#devto#dev#struct#fastkey
Reading 0:00
15s threshold

I had a cache keyed on a little struct. Three ints bundled together, nothing to it, the kind of value type you reach for when a plain tuple feels too anonymous. Over a batch of work I'd look things up in a Dictionary keyed by that struct a couple million times, and one day that lookup loop showed up in an allocation profile. Which made no sense to me. A dictionary lookup doesn't allocate. It hashes a key, walks a bucket, compares. Where's the garbage coming from?

The garbage was the key. Every lookup was boxing it, and I'd never typed a new to make that happen.

Who compares your keys

When you put something in 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 from EqualityComparer<TKey>.Default , and which comparer that resolves to depends on your type.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.