Why is AddRange faster than using a foreach loop?

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

    Potentially, AddRange can check where the value passed to it implements IList or IList. If it does, it can find out how many values are in the range, and thus how much space it needs to allocate... whereas the foreach loop may need to reallocate several times.

    Additionally, even after allocation, List can use IList.CopyTo to perform a bulk copy into the underlying array (for ranges which implement IList, of course.)

    I suspect you'll find that if you try your test again but using Enumerable.Range(0, 100000) for fillData instead of a List, the two will take about the same time.

提交回复
热议问题