Why is '397' used for ReSharper GetHashCode override?

自作多情 提交于 2019-11-26 09:16:35

问题


Like many of you, I use ReSharper to speed up the development process. When you use it to override the equality members of a class, the code-gen it produces for GetHashCode() looks like:

    public override int GetHashCode()
    {
        unchecked
        {
            int result = (Key != null ? Key.GetHashCode() : 0);
            result = (result * 397) ^ (EditableProperty != null ? EditableProperty.GetHashCode() : 0);
            result = (result * 397) ^ ObjectId;
            return result;
        }
    }

Of course I have some of my own members in there, but what I am wanting to know is why 397?

  • EDIT: So my question would be better worded as, is there something \'special\' about the 397 prime number outside of it being a prime number?

回答1:


Probably because 397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the hash somewhat, providing a better distribution of hash codes. There's nothing particularly special about 397 that distinguishes it from other primes of the same magnitude.




回答2:


Ben is correct, reflecting the Assembly you can see it's just a prime number they've chosen to use.




回答3:


The hash that resharper uses looks like a variant of the FNV hash. FNV is frequently implemented with different primes. There's a discussion on the appropriate choice of primes for FNV here.



来源:https://stackoverflow.com/questions/102742/why-is-397-used-for-resharper-gethashcode-override

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!