简体   繁体   中英

Why do “int” and “sbyte” GetHashCode functions generate different values?

We have the following code:

int i = 1;
Console.WriteLine(i.GetHashCode());  // outputs => 1

This make sense and the same happen whit all integral types in C# except sbyte and short. That is:

sbyte i = 1;
Console.WriteLine(i.GetHashCode());   //  outputs => 257

Why is this?

Because the source of that method ( SByte.GetHashCode ) is

public override int GetHashCode()
{
    return (int)this ^ ((int)this << 8);
}

As for why, well someone at Microsoft knows that..

Yes it's all about values distribution. As the GetHashCode method return type is int for the type sbyte the values are going to be distributed in intervals of 257. For this same reason for the long type will be colisions.

The reason is that it is probably done to avoid clustering of hash values.

As GetHashCode documentation says:

For the best performance, a hash function must generate a random distribution for all input. Providing a good hash function on a class can significantly affect the performance of adding those objects to a hash table. In a hash table with a good implementation of a hash function, searching for an element takes constant time (for example, an O(1) operation).

Also, as this excellent article explains:

Guideline: the distribution of hash codes must be "random" By a "random distribution" I mean that if there are commonalities in the objects being hashed, there should not be similar commonalities in the hash codes produced. Suppose for example you are hashing an object that represents the latitude and longitude of a point. A set of such locations is highly likely to be "clustered"; odds are good that your set of locations is, say, mostly houses in the same city, or mostly valves in the same oil field, or whatever. If clustered data produces clustered hash values then that might decrease the number of buckets used and cause a performance problem when the bucket gets really big.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM