var fillData = new List();
for (var i = 0; i < 100000; i++)
fillData.Add(i);
var stopwatch1 = new Stopwatch();
stopwatch1.Start();
var autoFill
The AddRange extension does not iterate through each item, but applies each item as a whole. Both foreach and .AddRange have a purpose. Addrange will win the contest of speed for your current situation.
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 ^^^
When using AddRange
the Collection can increase the size of the array once and then copy the values into it.
Using a foreach
statement the collection needs to increase size of the collection more than once.
Increasing thr size means copying the complete array which takes time.
Try out initialize intiial list capacity before manually adding items:
var manualFill = new List<int>(fillData.Count);
It is because the Foreach loop will add all the values that the loop is getting one a time and
the AddRange() method will gather all the values it is getting as a "chunk" and add that chunk at once to the specified location.
Simply understanding, it is just like you have a list of 10 items to bring from the market, which would be faster bringing all that one by one or all at single time.
This is like asking the waiter to bring you one beer ten times and asking him to bring you 10 beers at once.
What do you think is faster :)