Why is AddRange faster than using a foreach loop?
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 ^^^
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.