使用AddRange()</t>时,List <t>的内部数组是如何增加的

时间:2013-09-02 12:18:45

标签: c#

我正在循环浏览一个潜在的巨大(数百万项)数据集(存储在磁盘上)并拉出我要添加到List<T>的所选项目。当我将一个项目添加到列表中时,我会锁定它,因为有其他线程访问列表。

我正在尝试在两种可能的实现之间做出决定:

1)每次我需要添加项目时锁定列表。

2)使用我在找到项目时添加项目的临时列表,然后使用List<T>.AddRange()将该列表中的项目添加到块中(例如,当我找到1000个匹配项时)。这导致需要不经常请求锁定列表,但如果AddRange()仅增加容量足以完全容纳新项目,那么列表将最终重新调整大小。

我的问题是:据我了解,每次添加一个项目会导致每次达到容量时List<T>的内部容量增加一倍,但我不知道如何{ {1}}表现得很好。我认为它只增加了容纳新物品的容量,但我找不到任何方法来证实这一点。关于如何在MSDN上增加容量的描述对于Add()和AddRange()几乎是相同的,除了对于AddRange它说如果新计数大于容量,则容量增加而不是如果Count已经是与容量相同。
对我来说,这就好像使用AddRange()来添加足够的项目以超过当前容量将导致容量增加,就像使用Add()将超过当前容量一样。

那么,使用List<T>.AddRange()在一个大到足以超过当前容量的块中添加项目会导致容量增加到足以容纳新项目,还是会导致容量加倍?或者它是否做了我甚至没有考虑过的其他事情?

希望这很清楚,没有任何代码示例,因为它是关于List<T>.AddRange()如何实现的一般性问题,但如果不是,我将添加任何将使我的问题更清楚的问题。 如上所述,我已经阅读了MSDN文档,但找不到明确的答案。我也在这里搜索过任何类似的问题但找不到任何类似的问题,但如果有一个我错过的请指点我!

3 个答案:

答案 0 :(得分:7)

只要作为AddRange参数实现ICollection<T>传递的集合,数组大小只增加一次:

ICollection<T> collection2 = collection as ICollection<T>;
if (collection2 != null)
{
    int count = collection2.Count;
    if (count > 0)
    {
        this.EnsureCapacity(this._size + count);

    // (...)

否则标准枚举和每个元素的Insert方法调用都已完成:

}
else
{
    using (IEnumerator<T> enumerator = collection.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            this.Insert(index++, enumerator.Current);
        }
    }
}

修改

查看EnsureCapacity方法:

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

它会将数组大小增加Max(old_size * 2, min),并且因为它是使用min = old_size + count调用的,AddRange调用后的最终数组大小将设置为Max(old_size * 2, old_size + count) - 它会警惕当前List<T>使用AddRange方法添加的集合的大小和大小。

答案 1 :(得分:3)

容量增加的方式与Add相同。文档中未明确提及此问题,但查看源代码会显示AddAddRange内部都使用EnsureCapacity

答案 2 :(得分:0)

AddRange只会将大小增加到必要的数量。 因此,在AddRange函数中,您可以找到类似以下代码的内容:

if(capacity < count + items.Count)
{
  capacity = count + items.Count;
}

<击> 编辑:结果可能会逐个添加项目。

但是如果你正在使用非常大的数据集并且读取性能很重要,那么使用二叉树可能会更好。这将允许更快的搜索,添加,删除和部分锁定,使树的其余部分可用。树的最大问题是何时重新平衡。我在我的国际象棋游戏中使用了这个树,它在每次移动后都会重新平衡(因为这是需要删除的时候,这对于这个实现来说不是线程安全的):

namespace Chess
{
    /// <summary>
    /// Implements using a binary search tree.
    /// Is thread-safe when adding, not when removing.
    /// </summary>
    public class BinaryTree
    {
        public MiniMax.Node info;
        public BinaryTree left, right;

        /// <summary>
        /// Collisions are handled by returning the existing node. Thread-safe
        /// Does not recalculate height, do that after all positions are added.
        /// </summary>
        /// <param name="info">Connector in a tree structure</param>
        /// <returns>Node the position was already store in, null if new node.</returns>
        public MiniMax.Node AddConnection(MiniMax.Node chessNode)
        {
            if (this.info == null)
            {
                lock (this)
                {
                    // Must check again, in case it was changed before lock.
                    if (this.info == null)
                    {
                        this.left = new BinaryTree();
                        this.right = new BinaryTree();
                        this.info = chessNode;
                        return null;
                    }
                }
            }

            int difference = this.info.position.CompareTo(chessNode.position);

            if (difference < 0) return this.left.AddConnection(chessNode);
            else if (difference > 0) return this.right.AddConnection(chessNode);
            else
            {
                this.info.IncreaseReferenceCount();
                return this.info;
            }
        }

        /// <summary>
        /// Construct a new Binary search tree from an array.
        /// </summary>
        /// <param name="elements">Array of elements, inorder.</param>
        /// <param name="min">First element of this branch.</param>
        /// <param name="max">Last element of this branch.</param>
        public void CreateFromArray(MiniMax.Node[] elements, int min, int max)
        {
            if (max >= min)
            {
                int mid = (min + max) >> 1;
                this.info = elements[mid];

                this.left = new BinaryTree();
                this.right = new BinaryTree();

                // The left and right each have one half of the array, exept the mid.
                this.left.CreateFromArray(elements, min, mid - 1);
                this.right.CreateFromArray(elements, mid + 1, max);
            }
        }

        public void CollectUnmarked(MiniMax.Node[] restructure, ref int index)
        {
            if (this.info != null)
            {
                this.left.CollectUnmarked(restructure, ref index);

                // Nodes marked for removal will not be added to the array.
                if (!this.info.Marked)
                    restructure[index++] = this.info;

                this.right.CollectUnmarked(restructure, ref index);
            }
        }

        public int Unmark()
        {
            if (this.info != null)
            {
                this.info.Marked = false;
                return this.left.Unmark() + this.right.Unmark() + 1;
            }
            else return 0;
        }
    }
}