我想散列长度最大为 30 的字符串。如果时间紧迫,最好的办法是什么。该函数将被调用超过 1 亿次。目前我正在使用以下代码,
static UInt64 CalculateHash(string read, bool lowTolerance)
{
UInt64 hashedValue = 0;
int i = 0;
while (i < read.Length)
{
hashedValue += read.ElementAt(i) * (UInt64)Math.Pow(31, i);
if (lowTolerance) i += 2;
else i++;
}
return hashedValue;
}
最佳答案
static UInt64 CalculateHash(string read)
{
UInt64 hashedValue = 3074457345618258791ul;
for(int i=0; i<read.Length; i++)
{
hashedValue += read[i];
hashedValue *= 3074457345618258799ul;
}
return hashedValue;
}
这是 Knuth 哈希。您也可以使用 Jenkins 。
关于c# - C#中字符串的快速哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9545619/