Why is AddRange faster than using a foreach loop?

后端 未结 10 2365
长情又很酷
长情又很酷 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 03:05

    i suppose this is the result of optimisation of memory allocation. for AddRange memory allocates only once, and while foreach on each iteration reallocation is done.

    also may be there are some optimisations in AddRange implementation (memcpy for example)

提交回复
热议问题