Why is AddRange faster than using a foreach loop?

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

    The AddRange extension does not iterate through each item, but applies each item as a whole. Both foreach and .AddRange have a purpose. Addrange will win the contest of speed for your current situation.

    0 讨论(0)
  • 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<int>(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<T> is2 = collection as ICollection<T>;
    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 ^^^
    
    0 讨论(0)
  • 2020-11-29 02:43

    When using AddRange the Collection can increase the size of the array once and then copy the values into it.

    Using a foreach statement the collection needs to increase size of the collection more than once.

    Increasing thr size means copying the complete array which takes time.

    0 讨论(0)
  • 2020-11-29 02:50

    Try out initialize intiial list capacity before manually adding items:

    var manualFill = new List<int>(fillData.Count); 
    
    0 讨论(0)
  • 2020-11-29 02:51

    It is because the Foreach loop will add all the values that the loop is getting one a time and
    the AddRange() method will gather all the values it is getting as a "chunk" and add that chunk at once to the specified location.

    Simply understanding, it is just like you have a list of 10 items to bring from the market, which would be faster bringing all that one by one or all at single time.

    0 讨论(0)
  • 2020-11-29 02:52

    This is like asking the waiter to bring you one beer ten times and asking him to bring you 10 beers at once.

    What do you think is faster :)

    0 讨论(0)
提交回复
热议问题