I have this legacy code where there's often this pattern of a dictionary of string to dictionary of string to some object.
Dictionary<string, Dictionary<string, someobject>>
retrieval of an object is then always based on two times TryGetValue
Dictionary<string, Dictionary<string, Dealer>> dicDealers ...
if (dicDealers.TryGetValue(lab, out dealers))
dealers.TryGetValue(dealerNumber, out dealer);
Now I was thinking it should be more efficient when the two string keys are combined into a key struct with two string members so the objects get retrieved in one go. So I created a Key struct which overrides GetHashCode and Equals calculating a hash on bots key members.
public struct Key<T>
{
private T mKey1;
private T mKey2;
public Key(T t, T u)
{
mKey1 = t;
mKey2 = u;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
Key<T> rhs = (Key<T>)obj;
return mKey1.Equals(rhs.mKey1) && mKey2.Equals(rhs.mKey2);
}
public override int GetHashCode()
{
int hash = 17;
hash = ((hash << 5) - hash) + mKey1.GetHashCode();
hash = ((hash << 5) - hash) + mKey2.GetHashCode();
return hash;
}
}
Now you can do it at once.
Key<string> key = new Key<string>(lab, dealerNumber);
if (dicDealers.TryGetValue(key, out someobject))
{
...
}
I thought it should be faster but it turns out both ways are about as fast. How can that be? Can I do something to make the second technique run faster?