-4

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?

Richard
  • 29,854
  • 11
  • 77
  • 120
Eluvium
  • 163
  • 1
  • 4
  • 17

1 Answers1

2

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.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 1
    In this case it likely only does one copy. The copy algorithm for list is a doubling action. The first loop will do many resizes until you get past 10000 items, the second loop one is guaranteed to do zero or one resize (because the first one puts it at least an 10000 items or more), but it'll be a large one. – Adam Houldsworth Apr 27 '15 at 14:51
  • It helped me to understand! Thanks a lot!! – Eluvium Apr 27 '15 at 14:57