且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中字符串的快速哈希函数

更新时间:2023-11-07 15:05:28

 静态UINT64 CalculateHash(串读)
{
    UINT64 HASHEDVALUE = 3074457345618258791ul;
    的for(int i = 0; I< read.Length;我++)
    {
        HASHEDVALUE + =读[I]
        HASHEDVALUE * = 3074457345618258799ul;
    }
    返回HASHEDVALUE;
}

这是一个高德纳哈希值。您也可以使用詹金斯

I want to hash a string of length upto 30. What will be the best idea to do that if time is my concern. The function will be called over 100 million times. currently I am using the foloowing code,

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;
}

This is a Knuth hash. You can also use Jenkins.