Overriding GetHashCode()

前端 未结 3 678
臣服心动
臣服心动 2021-01-17 08:19

In this article, Jon Skeet mentioned that he usually uses this kind of algorithm for overriding GetHashCode().

public override int GetHashCode()
{
          


        
3条回答
  •  春和景丽
    2021-01-17 08:45

    I personally tend to return a different numeric value for each implementation of GetHashCode() in a class which has no immutable fields. This means if I have a dictionary containing different implementing types, there is a chance the different instances of different types will be put in different buckets.

    For example

    public class A
    {
        // TODO Equals override
    
        public override int GetHashCode()
        {
            return 21313;
        } 
    }
    
    public class B
    {
        // TODO Equals override
    
        public override int GetHashCode()
        {
            return 35507;
        } 
    }
    

    Then if I have a Dictionary containing instances of A, B and other types , the performance of the lookup will be better than if all the implementations of GetHashCode returned the same numeric value.

    It should also be noted that I make use of prime numbers to get a better distribution.

    As per the comments I have provided a LINQPad sample here which demonstrates the performance difference between using return 1 for different types and returning a different value for each type.

提交回复
热议问题