本文介绍了.NET ConcurrentDictionary初始容量设置为任意素数,而不是预期的在MSDN例如文档的能力。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在看 MSDN文档ConcurrentDictionary 和我在看到这个例如code:

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 the ConcurrentDictionary.
// So set the initial capacity to some prime number above that, to ensure that
// the ConcurrentDictionary does not need to be resized while initializing it.
int NUMITEMS = 64;
int initialCapacity = 101;

作为参考,在MSDN例如字典初始化如下:

For reference, the dictionary in the MSDN example is initialized as follows:

ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(Environment.ProcessorCount * 2, initialCapacity);
for (int i = 0; i < NUMITEMS; i++) cd[i] = i * i;

在这个例子中,字典是永远不会超过64个项目。为什么不设置初始容量为64个,而不是一个看似随意的质数大于64?该评论说,这是为了确保词典不需要初始化时它被调整,但为什么类似的字典参数:initialCapacity = 64需要被调整?为什么这个素数选择?

In the example, the dictionary is never going to contain more than 64 items. Why not set the initial capacity to 64, rather than to a seemingly arbitrary prime number greater than 64? The comment says that this is to ensure that the dictionary does not need to be resized while initializing it, but why would a similar dictionary with initialCapacity=64 need to be resized? Why was this prime number chosen?

推荐答案

字典或哈希表依赖于散列的关键在于得到较小的索引来查找到相应的存储(阵列)。这样的选择哈希函数的是非常重要的。典型的选择是让哈希$ C $一个关键的C(让我们获得良好的随机分布),然后用一个素数除以code和使用提醒索引桶的固定号码。这允许转换任意大的哈希codeS到有界集的小号码我们可以定义一个数组查找到。所以其重要的是要有数组大小在素数,然后为大小最好选择成为素数比所要求的容量。而这正是字典实现不执行。

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.

所以基本上任何模n(n为素数)的字典的实施需要的能力是在素数。所以,如果你说的,所需容量为X,那么这些实现通常会选择比所需的能力下一个更大的引物的数量。

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.

这篇关于.NET ConcurrentDictionary初始容量设置为任意素数,而不是预期的在MSDN例如文档的能力。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:14