How do you efficiently combine hash codes?
When combining hash codes I started by generating a large string and then hashing that. However that was inefficient, so instead I was referred to this simple arithmetic solution on StackOverflow provided by Jon Skeet himself!
unchecked
{
int hash = 17;
hash = hash * 31 + firstField.GetHashCode();
hash = hash * 31 + secondField.GetHashCode();
return hash;
}
How much more efficient is this than string concatenation?
TLDR: Very! Below is a chart of the average number of ticks it takes to calculate a hash by both generating a string and Jon's method of adding ints. Each test is an average of 100,000 iterations.
Number of Keys | Avg Ticks for String | Avg Ticks for Int | Performance Increase |
---|---|---|---|
2 | 0.90 | 0.15 | 500% |
5 | 2.08 | 0.25 | 732% |
10 | 3.77 | 0.37 | 918% |
20 | 7.30 | 0.64 | 1040% |
50 | 18.97 | 1.33 | 1326% |