Fylax Fylax - 22 days ago 8
C# Question

How can I access a Dictionary through a key hashcode?

I have a dictionary like that:

Dictionary<MyCompositeKey, int>


Clearly
MyCompositeKey
is a class I designed which implements
IEqualityComparer
and thus has a
GetHashCode
method.

As far as I know, dictionary uses the key's hash to access the value, so here's my question:

While I can easily access the value via
dict.TryGetValue(new MyCompositeKey(params))
, I wanted to get rid off the
new
overhead on each access.

For this reason I was wondering if there's a way to access the value directly from key's hash (which I can compute with a very lower overhead).

Answer

There is no way to do that.

Note that hash collisions may occur, so there could be many keys in the Dictionary<,> matching the given hash. We need Equals to find out which (if any) is correct.

You talk about new overhead. Are you sure it is significant in your case?

If it is, you could consider making MyCompositeKey an immutable struct instead of a class. It might be faster in some cases, eliminating the need for the garbage collector to remove all those "loose" keys from memory.

If MyCompositeKey is a struct, the expression new MyCompositeKey(params)) only loads all the params onto the call stack (or CPU registers or whatever the run-time figures is best).