【问题标题】:what is the max limit of data into list<string> in c#?c# 中 list<string> 的最大数据限制是多少?
【发布时间】:2011-04-23 20:12:32
【问题描述】:

我可以向 List 添加多少值?

例如:

List<string> Item = runtime data

数据大小不固定。它可能是 10 000 或超过 1 000 000。我已经用 Google 搜索过,但没有找到确切的答案。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    理论上,List&lt;T&gt; 的当前实现中可以存储的最大元素数为 Int32.MaxValue - 刚刚超过 20 亿。

    在当前 Microsoft 的 CLR 实现中,最大对象大小限制为 2GB。 (其他实现,例如 Mono,可能没有这个限制。)

    您的特定列表包含字符串,它们是引用类型。引用的大小将是 4 或 8 个字节,具体取决于您是在 32 位还是 64 位系统上运行。这意味着您可以存储的字符串数量的实际限制在 32 位上约为 5.36 亿,在 64 位上约为 2.68 亿。

    实际上,在达到这些限制之前,您很可能会用完可分配内存,尤其是在 32 位系统上运行时。

    【讨论】:

    • 除了固定的上限,重复创建和释放大数组会导致分配不一致,即使内存分配更合理(大约 100 MB)也会导致 OutOfMemoryException,即使内存实际上是可用的。如果您必须处理非常大的集合,这将影响您的设计。
    【解决方案2】:

    2147483647 因为 List 外的所有函数都使用 int。

    来自 mscorlib:

    private T[] _items;
    private int _size;
    
    public T this[int index]
    {
      get
        {
          //...
        }
    }
    

    【讨论】:

      【解决方案3】:

      list.Count() 属性是 int32,因此它必须是 int32 的最大限制,但您的列表在此限制上的表现是一个很好的观察。

      如果你做一些列表操作,理论上会更线性。

      我会说,如果您有大量关于 .net 4.0 中的并行集合的项目,这将使您的列表操作更具响应性。

      【讨论】:

        【解决方案4】:

        根据List的实现

        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;
                }
            }
        

        现在导航到这个 Array.MaxArrayLength:

        internal const int MaxArrayLength = 2146435071;
        

        【讨论】:

          【解决方案5】:

          您可以使用 List 轻松绕过此限制。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-08-31
            • 1970-01-01
            • 2011-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-02-28
            • 2017-01-28
            • 1970-01-01
            相关资源
            最近更新 更多