.NET ConcurrentDictionary initial capacity set to arbitrary prime number rather than expected capacity in MSDN example documentation. Why?

前端 未结 1 2007
既然无缘
既然无缘 2021-02-20 09:26

I was just looking at the MSDN documentation for ConcurrentDictionary, and I saw this in the \"example\" code:

// We know how many items we want to insert into t         


        
相关标签:
1条回答
  • 2021-02-20 10:28

    Dictionary or hash table relies on hashing the key to get a smaller index to look up into corresponding store (array). So choice of hash function is very important. Typical choice is to get hash code of a key (so that we get good random distribution) and then divide the code by a prime number and use reminder to index into fixed number of buckets. This allows to convert arbitrarily large hash codes into a bounded set of small numbers for which we can define an array to look up into. So its important to have array size in prime number and then the best choice for the size become the prime number that is larger than the required capacity. And that's exactly dictionary implementation does.

    So basically any Modulo N (n being prime number) dictionary implementation will need its capacity to be in prime number. So if you say, required capacity is X then these implementation will typically choose next larger primer number than required capacity.

    0 讨论(0)
提交回复
热议问题