净GetHash code位换档操作 [英] .Net GetHashcode Bit Shifting Operation

查看:203
本文介绍了净GetHash code位换档操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找通过一些.NET源昨天,看到沿此线的东西的GetHash code几种实现方式:

I was looking through some of the .net source yesterday and saw several implementations of GetHashcode with something along the lines of this:

(i1 << 5) + i ^ i2

我明白了code是做什么,为什么。我想知道的是他们为什么使用(I1&LT;小于5)的 + 我来代替(I1&LT;小于5)。 -

I understand what the code is doing and why. What I want to know is why they used (i1 << 5) + i instead of (i1 << 5) - i.

我见过使用-i,因为这相当于31这是素相乘,但微软的方式相当于33具有11和3相乘的因素,因此不是素数大多数框架。

Most frameworks I've seen use -i because that's equivalent to multiplying by 31 which is prime, but the Microsoft way is equivalent to multiplying by 33 which has 11 and 3 as factors and thus isn't prime.

有没有已知的理由呢?任何合理的假设?

Is there a known justification for this? Any reasonable hypotheses?

推荐答案

我问在math.stackexchange.com同样的问题:的 33 好奇的属性。

I asked the same question on math.stackexchange.com: Curious Properties of 33.

数学家和我做的课题研究中的猜想让我相信,答案是这样的:

The conjecture among mathematicians and the research I did on the topic leads me to believe that the answer is this:

好吧,我找到了原因Microsoft使用33这就是所谓的伯恩斯坦   哈希值。事实证明,33有一些能产生一个魔法属性   哈希codeS的良好分布和有很少的理论   了解为什么。

Okay, I found out why Microsoft uses 33. That's called the Bernstein Hash. It turns out that 33 has some magical properties that produce a good distribution of hash codes and there's very little theoretical knowledge as to why.

基本上,熵和速度比较,伯恩斯坦的确不够好,是相当活泼。丹·伯恩斯坦,谁想出了恒定33的家伙,是不是能说明什么财产33产生的散列这么好的分配。

Basically, in entropy and speed comparisons, Bernstein does well enough and is quite snappy. Dan Bernstein, the guy who came up with the constant 33, wasn't able to explain what property of 33 produced such a good distribution of hashes.

若干论文已被写入比较散列函数,并证实了这一发现没有进一步说明采用33进一步的好处,我找不到为什么Java使用31来代替。这似乎是一个数学和编程的奥秘至今。

Several papers have been written comparing hash functions and have corroborated this finding without further explaining the benefit of using 33. Further, I couldn't find why Java uses 31 instead. It appears to be a mathematical and programming mystery to date.

这篇关于净GetHash code位换档操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆