Sunday, August 1, 2010

GetHashCode's preformance really matters if you use it as a dictionary key alot

Just a quick post about a surprisingly small change that improved performance in magecrawl's skill tree view. I have a custom point class since there doesn't exist one inside c# outside of some GUI toolkits I don't want to force dependencies on.Since I overrode Equals, the compiler told me to override GetHashCode. I did so the naive way:
public override int GetHashCode()
{
    return X ^ Y ^ base.GetHashCode();
}

I have a spot in a tight loop that needs to lookup information based upon its position. I was previously using a List with a where LINQ call, which was insanely slow when I scaled up the number of skills. I figured this out using profiling and changed it to a dictionary. However, it was still too slow, so I read up on GetHashCode more and realized I could change GetHashCode for point to read:

public override int GetHashCode()
{
    return X ^ Y;
}

I didn't keep track of the numbers, but this very visibly made a huge difference. Keep GetHashCode in mind when you have data structures that are used as keys in large dictionaries. A small change can make a big improvement.

No comments: