Using byte array as dictionary key

This question already has an answer here:

  • What is the best algorithm for an overridden System.Object.GetHashCode? 17 answers

  • A better choice for a hash could be something like this:

    public override int GetHashCode(byte[] obj)
    {
        int hash = 0;
        for (int i = 0; i < obj.Length; i++)
        {
            exponents = [0, 8, 16, 24];
            exponent = exponents[i % 4];
    
            unchecked
            {
                hash += obj[i] * (1 << i);
            }
        }
        return hash;
    }
    

    Conceptually, this converts each chunk of 4 bytes into an int, since both are 32 bits, and then adds them together with standard integer overflow. So, all unique byte arrays of length 4 or less will map to different hash codes and (given random data) larger arrays should be well distributed in the hash space. If you're expecting lots of very similar arrays, or arrays that repeat every 4 or something, this might not be the best strategy.


    MurmurHash is pretty fast and quite simple. There's a number of .NET-based implementations, but I don't exactly know how performant are they.

    链接地址: http://www.djcxy.com/p/39768.html

    上一篇: 具有三个Int16值的C#GetHashCode?

    下一篇: 使用字节数组作为字典键