为什么是“397”? 用于 ReSharper GetHashCode 覆盖?
和你们中的许多人一样,我使用 ReSharper 来加快开发过程。 当您使用它来覆盖类的相等成员时,它为 GetHashCode()
生成的代码生成看起来像:
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;
}
}
当然我有一些我自己的成员,但我想要什么要知道为什么是397?
- 编辑:所以我的问题最好措辞为,除了素数之外,397素数还有什么“特别”之处吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
resharper 使用的哈希看起来像是 FNV< /a> 哈希。 FNV 经常使用不同的素数来实现。 此处讨论了 FNV 素数的适当选择。
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.
可能是因为 397 是一个足够大小的质数,足以导致结果变量溢出并在某种程度上混合散列的位,从而提供更好的散列码分布。 397 与其他同量级素数相比并没有什么特别之处。
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.