c# - List<T> 和 ArrayList 默认容量

标签 c# .net performance algorithm memory-management

我一直在研究 .NET 的 ListArrayList 实现 Reflector .

在查看 Add(T item) 时,我遇到了这个。EnsureCapacity(this._size + 1):

public void Add(T item)
{
    if (this._size == this._items.Length)
    {
       this.EnsureCapacity(this._size + 1);
    }
    this._items[this._size++] = item;
    this._version++;
}

所以 EnsureCapacity 看起来像这样:

private void EnsureCapacity(int min)
{
    if (this._items.Length < min)
    {
        int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
        if (num < min)
        {
            num = min;
        }
        this.Capacity = num;
    }
}

为什么内部Capacity默认为4,然后以2的倍数递增(即:double)?

最佳答案

关于需要调整大小时加倍的原因如下。假设您要将 n 项插入到 List 中。我们将调整列表的大小不超过 log n 次。因此,将 n 项插入 List 将花费最坏情况下的 O(n) 时间,因此插入在 amortized time 中保持不变。 .此外,浪费的空间量受 n 限制。任何恒定比例增长的策略都会导致恒定的摊销插入时间和线性浪费的空间。比恒定比例增长更快的增长可能导致更快的插入,但代价是更多的空间浪费。增长速度慢于恒定比例增长可能会减少空间浪费,但代价是插入速度较慢。

默认容量使得很少有内存被浪费(并且从小开始没有坏处,因为正如我们刚刚看到的那样,从时间/空间的角度来看,双倍调整策略是好的)。

关于c# - List<T> 和 ArrayList 默认容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1665298/

相关文章:

C# Executable 执行目录

c# - Xamarin Forms - 如何创建可以输入数量的显示警报?

c# - 仅当 listView 不为空时,如何才能激活/启用 contextmenustrip 菜单?

c# - 使用更多方法提高C#中Parallel.For的性能

php - MySQL JSON 数据类型是否不利于数据检索的性能?

c# - 如何使用Mvvm将页面推送到MasterDetailPage

c# - TPL 数据流 : Bounded capacity and waiting for completion

c# - 如何使用 Azure Active Directory .NET SDK 删除 AppRoleAssignment?

c# - 将具有两列的 SQL IN 子句转换为 LINQ

performance - 在 init 或处理函数中读取模板?