Why setting HashTable's length to a Prime Number is a good practice?

后端 未结 3 1138
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 19:47

I was going through Eric Lippert\'s latest Blog post for Guidelines and rules for GetHashCode when i hit this para:

We could be even more clever here;

3条回答
  •  旧巷少年郎
    2020-12-13 19:56

    Because this produces a better hash function and reduces the number of possible collisions. This is explained in Choosing a good hashing function:

    A basic requirement is that the function should provide a uniform distribution of hash values. A non-uniform distribution increases the number of collisions, and the cost of resolving them.

    The distribution needs to be uniform only for table sizes s that occur in the application. In particular, if one uses dynamic resizing with exact doubling and halving of s, the hash function needs to be uniform only when s is a power of two. On the other hand, some hashing algorithms provide uniform hashes only when s is a prime number.

提交回复
热议问题