A fast hash function for string in C#

后端 未结 4 1474
后悔当初
后悔当初 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:31

    To speed up your implementation, the (UInt64)Math.Pow(31, i) call should be replaced by a lookup: pre-calculate a table of the first 30 powers of 31, and use it at runtime. Since the limit on length is 30, you need only 31 element:

    private static unsigned long[] Pow31 = new unsigned long[31];
    
    static HashCalc() {
        Pow31[0] = 1;
        for (int i = 1 ; i != Pow31.Length ; i++) {
            Pow31[i] = 31*Pow31[i-1];
        }
    }
    
    // In your hash function...
    hashedValue += read.ElementAt(i) * Pow31[i];
    

提交回复
热议问题