Search code examples
c#.netstopwatch

Why property "ElapsedTicks" of List not equal to "ElapsedTicks" of Array?


For example I have the following code implements Stopwatch:

var list = new List<int>();
var array = new ArrayList();

Stopwatch listStopwatch = new Stopwatch(), arrayStopwatch = new Stopwatch();

listStopwatch.Start();
for (int i =0; i <=10000;i++)
{
    list.Add(10);
}

listStopwatch.Stop();

arrayStopwatch.Start();
for (int i = 0; i <= 10000; i++)
{
    list.Add(10);
}
arrayStopwatch.Stop();

Console.WriteLine(listStopwatch.ElapsedTicks > arrayStopwatch.ElapsedTicks);

Why this values are not equal?


Solution

  • Different code is expected to produce different timing.

    Second loop adds to array as question imply

    One most obvious difference is boxing in ArrayList - each int is stored as boxed value (created on heap instead of inline for List<int>).

    Second loop adds to list as sample shows

    growing list requires re-allocation and copying all elements which may be slower for second set of elements if in particular range it will hit more re-allocations (as copy operation need to copy a lot more elements each time).

    Note that on average (as hinted by Adam Houldsworth) re-allocation cost the same (as they happen way lest often when array grows), but one can find set of numbers when there are extra re-allocation in on of the cases to get one number consistently different than another. One would need much higher number of items to add for difference to be consistent.