Why is AddRange faster than using a foreach loop?

后端 未结 10 2384
长情又很酷
长情又很酷 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:40

    If you are using Add, it is resizing the inner array gradually as needed (doubling), from the default starting size of 10 (IIRC). If you use:

    var manualFill = new List(fillData.Count);
    

    I expect it'll change radically (no more resizes / data copy).

    From reflector, AddRange does this internally, rather than growing in doubling:

    ICollection is2 = collection as ICollection;
    if (is2 != null)
    {
        int count = is2.Count;
        if (count > 0)
        {
            this.EnsureCapacity(this._size + count);
            // ^^^ this the key bit, and prevents slow growth when possible ^^^
    

提交回复
热议问题