var fillData = new List<int>();
for (var i = 0; i < 100000; i++)
fillData.Add(i);
var stopwatch1 = new Stopwatch();
stopwatch1.Start();
var autoFill = new List<int>();
autoFill.AddRange(fillData);
stopwatch1.Stop();
var stopwatch2 = new Stopwatch();
stopwatch2.Start();
var manualFill = new List<int>();
foreach (var i in fillData)
manualFill.Add(i);
stopwatch2.Stop();
When I take 4 results from stopwach1 and stopwach2, stopwatch1 has always lower value than stopwatch2. That means addrange is always faster than foreach.
Does anyone know why?
Potentially,
AddRangecan check where the value passed to it implementsIListorIList<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 theforeachloop may need to reallocate several times.Additionally, even after allocation,
List<T>can useIList<T>.CopyToto perform a bulk copy into the underlying array (for ranges which implementIList<T>, of course.)I suspect you’ll find that if you try your test again but using
Enumerable.Range(0, 100000)forfillDatainstead of aList<T>, the two will take about the same time.