我可以向List中添加多少个值?
例如:
List<string> Item = runtime data
数据大小不固定,可能是10,000或超过1,000,000。我已经搜索了谷歌,但没有找到确切的答案。
当前实现的 List<T>
可以存储的元素最大数量,在理论上是 Int32.MaxValue
- 稍微超过20亿。
在当前的 Microsoft CLR 实现中,有一个2GB的最大对象大小限制。(可能其他实现,例如 Mono,没有这个限制。)
您特定的列表包含字符串,这些字符串是引用类型。引用的大小将是4或8字节,具体取决于您正在运行的是32位还是64位系统。这意味着您可以存储的字符串的实际限制将大约是32位系统上的5.36亿或64位系统上的2.68亿。
实际上,在达到这些限制之前,您很可能会耗尽可分配的内存,尤其是在运行32位系统时。
由于List的所有函数都使用int类型,因此最大值为2147483647。
来自mscorlib:
private T[] _items;
private int _size;
public T this[int index]
{
get
{
//...
}
}
list.Count()属性是Int32类型的,因此它必须是Int32的最大限制,但是您的列表如何在此限制上执行是一个不错的观察。
如果您进行一些列表操作,理论上它将是线性的。
我想说,如果您有大量项目,请考虑使用.NET 4.0中的Parallel Collections,这将使您的列表操作更具响应性。
private void EnsureCapacity(int min) {
if (_items.Length < min) {
int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
internal const int MaxArrayLength = 2146435071;
你可以用List<char[]>轻松地解决这个限制。