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

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

问题描述

.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 一样增长,每次容量增加时都会增加一倍,并且每次重新分配都是昂贵的,为什么不将大小预先设置为您知道可以保存数据的东西,有一些额外的空间以防万一?如果初始容量是 100,而我知道我只需要 12 个左右,那么剩余的内存似乎没有分配.

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.

推荐答案

如果没有记录默认值,原因很可能是最佳初始容量是一个实现细节,并且可能会在框架版本.也就是说,您不应编写假定某个默认值的代码.

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.

也就是说,您可以使用 Reflector 确定默认值.例如,在 .NET 4.0(可能还有以前的版本)中,

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

  • 一个列表初始化为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.

字典也初始化为容量为 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天全站免登陆