A fast hash function for string in C#

后端 未结 4 1487
后悔当初
后悔当初 2020-12-02 21:03

I want to hash a string of length up-to 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 u

4条回答
  •  余生分开走
    2020-12-02 21:18

    First of all, consider using GetHashCode().

    A simple improvement on your existing implementation:

    static UInt64 CalculateHash(string read, bool lowTolerance)
    {
        UInt64 hashedValue = 0;
        int i = 0;
        ulong multiplier = 1;
        while (i < read.Length)
        {
            hashedValue += read[i] * multiplier;
            multiplier *= 37;
            if (lowTolerance) i += 2;
            else i++;
        }
        return hashedValue;
    }
    

    It avoids the expensive floating point calculation, and the overhead of ElementAt.

    Btw (UInt64)Math.Pow(31, i) doesn't work well for longer strings. Floating point rounding will lead to a multiplier of 0 for characters beyond 15 or so.

提交回复
热议问题