Potentially, AddRange
can check where the value passed to it implements IList
or IList<T>
. 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<T>
can use IList<T>.CopyTo
to perform a bulk copy into the underlying array (for ranges which implement IList<T>
, 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<T>
, the two will take about the same time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…