Search code examples
c#performancegethashcode

How to reduce complexity of GetHashCode


I want to decrease my code execution time. Looking at some testing results, I found out that GetHashCode() took 21,62% of my execution time.

I also got a warning:

Warning 1 DA0010: .*.GetHashCode() = 7,63; GetHashCode functions should be cheap and not allocate any memory. Reduce complexity of hash code function if possible.

Code Snippets:

My GetHashCode() in Field Class:

    public override int GetHashCode()
    {
        int hash = 7;
        hash = (hash * 13) + this.Coordinate.GetHashCode();
        return hash;
    }

My GetHashCode() in Coordinate Class:

    public override int GetHashCode()
    {
        int hash = 17;

        hash = (hash * 23) + this.Row.GetHashCode();
        hash = (hash * 23) + this.Column.GetHashCode();

        return hash;
    }

Edit: Row and Column are just byte variables. I just call their property which returns a byte in the get accessor

My GetHashCode() in Sudoku Class:

    public override int GetHashCode()
    {
        int hash = 7;

        hash = (hash * 5) + this.Grid.GetHashCode();

        return hash;
    }

Edit: Grid is just a multidimensional array of type: Field[,], I just call it's Property here which returns a Field[,] grid through it's get accessor.

Questions: How can I greatly decrease the complexity of my GetHashCode() and increase it's performance? Why is the performance of GetHashCode() method so low?


Solution

  • I suspect you'll find that GetHashCode isn't your problem. If you're spending > 20% of your time in GetHashCode, you must be doing a whole lot of dictionary lookups. Or you're using the hash code for something you probably shouldn't be using it for.

    GetHashCode might be the manifestation of the performance problem, but it's almost certainly not the cause.