我只是在查看ConcurrentDictionary的MSDN文档,我在"示例"代码中看到了这一点:
// 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;
Run Code Online (Sandbox Code Playgroud)
作为参考,MSDN示例中的字典初始化如下:
ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(Environment.ProcessorCount * 2, initialCapacity);
for (int i = 0; i < NUMITEMS; i++) cd[i] = i * i;
Run Code Online (Sandbox Code Playgroud)
在该示例中,字典永远不会包含超过64个项目.为什么不将初始容量设置为64,而不是设置为大于64的看似随意的素数?评论说这是为了确保字典在初始化时不需要调整大小,但为什么需要调整initialCapacity = …