
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
600
|
Chapter 11: Data Structures and Algorithms
This algorithm will produce a good distributed hash code for your object and has the
added benefit of being able to employ any data type. This is a high-performing algo-
rithm for simple, moderately complex, and even many complex objects. However,
for extremely complex objects—ones that contain many large arrays, large
Hashtables, or other objects that use a slower hash-code algorithm—this algorithm
will start performing badly. In this extreme case, you may want to consider switch-
ing to another hash-code algorithm to speed performance or simply paring down the
amount of fields used in the calculation. Be careful if you choose this second method
to increase performance; you could inadvertently cause the algorithm to produce
similar values for differing objects. The code for the calculated hash method is:
public int CalcHash(short someShort, int someInt, long someLong,
float someFloat, object someObject)
{
int hashCode = 7;
hashCode = hashCode * 31 + (int)someShort;
hashCode = hashCode * 31 + someInt;
hashCode = hashCode * 31 +
(int)(someLong ^ (someLong >> 32));
long someFloatToLong = (long)someFloat;
hashCode = hashCode * 31 +
(int)(someFloatToLong ^ (someFloatToLong >> 32));
if (someObject != null)
{
hashCode = hashCode * 31 +
someObject.GetHashCode( ...