Why is AddRange faster than using a foreach loop?

后端 未结 10 2364
长情又很酷
长情又很酷 2020-11-29 02:19
var fillData = new List();
for (var i = 0; i < 100000; i++)
     fillData.Add(i);

var stopwatch1 = new Stopwatch();
stopwatch1.Start();

var autoFill          


        
10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 02:57

    The dissassembly from reflector for the List AddRange method has the following code

    ICollection is2 = collection as ICollection;
    if (is2 != null)
    {
        int count = is2.Count;
        if (count > 0)
        {
            this.EnsureCapacity(this._size + count);
            if (index < this._size)
            {
                Array.Copy(this._items, index, this._items, index + count, this._size - index);
            }
            if (this == is2)
            {
                Array.Copy(this._items, 0, this._items, index, index);
                Array.Copy(this._items, (int) (index + count), this._items, (int) (index * 2), (int) (this._size - index));
            }
            else
            {
                T[] array = new T[count];
                is2.CopyTo(array, 0);
                array.CopyTo(this._items, index);
            }
            this._size += count;
        }
    }
    

    As you can see there are some optimizations like EnsureCapacity() call and using Array.Copy().

提交回复
热议问题