集合类型,例如初始容量字典,列表 [英] Initial capacity of collection types, e.g. Dictionary, List

查看:359
本文介绍了集合类型,例如初始容量字典,列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.net中的某些集合类型有一个可选的初始容量的构造函数的参数。例如:

Certain collection types in .Net have an optional "Initial Capacity" constructor parameter. For example:

Dictionary<string, string> something = new Dictionary<string,string>(20);

List<string> anything = new List<string>(50);

我似乎无法找到默认的初始容量是什么MSDN上的这些对象。

I can't seem to find what the default initial capacity is for these objects on MSDN.

如果我知道,我将只存储12左右的项目在字典中,没有有意义设置初始容量为类似20?

If I know I will only be storing 12 or so items in a dictionary, doesn't it make sense to set the initial capacity to something like 20?

我的理由是,假设容量变得像它为一个StringBuilder,其中每个时间的能力被击中加倍,并且每个再分配是昂贵的,为什么不$ P $对 - 设置你知道将保留大小的东西你的数据,有一些额外的空间,以防万一?如果初始容量为100,我知道我将只需要十几,它好像是内存的其余部分分配给什么。

My reasoning is, assuming that the capacity grows like it does for a StringBuilder, which doubles each time the capacity is hit, and each reallocation is costly, why not pre-set the size to something you know will hold your data, with some extra room just in case? If the initial capacity is 100, and I know I will only need a dozen or so, it seems as though the rest of that memory is allocated for nothing.

推荐答案

如果缺省值不记录,原因可能是最佳的初始容量是实施细节与主体之间的变更框架的版本。也就是说,你不应该写code假定某个默认值。

If the default values are not documented, the reason is likely that the optimal initial capacity is an implementation detail and subject to change between framework versions. That is, you shouldn't write code that assumes a certain default value.

构造过载容量是案件中,你知道更好比项目数是可以预期的类。例如,如果您创建的50个值的集合,知道这个数字永远不会增加,你可以初始化集合,容量为50,所以不会有调整,如果默认的能力较低。

The constructor overloads with a capacity are for cases in which you know better than the class what number of items are to be expected. For example, if you create a collection of 50 values and know that this number will never increase, you can initialize the collection with a capacity of 50, so it won't have to resize if the default capacity is lower.

这就是说,你可以使用反射确定的默认值。例如,在.NET 4.0(也可能是previous版本也一样),

That said, you can determine the default values using Reflector. For example, in .NET 4.0 (and probably previous versions as well),

  • 一个List&LT; T&GT;用容量为0初始化当第一项被加入,但重新初始化到一个容量为4。接着,每当容量达到,容量加倍。

  • a List<T> is initialized with a capacity of 0. When the first item is added, it is reinitialized to a capacity of 4. Subsequently, whenever the capacity is reached, the capacity is doubled.

字典&LT; T&GT;被intialized的容量为0,以及。但它采用了完全不同的算法来增加容量。它增加的能力总是素数

a Dictionary<T> is intialized with a capacity of 0 as well. But it uses a completely different algorithm to increase the capacity: it increases the capacity always to prime numbers.

这篇关于集合类型,例如初始容量字典,列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆