I want to determine the time spent on deleting the elements of the collection, but for some reason, regardless of the number of elements, it gives 0 ms

static void Main(string[] args) { Stopwatch stopWatch = new Stopwatch(); Stopwatch sw = new Stopwatch(); ArrayList al = new ArrayList(); Console.Write("Π’Π²Π΅Π΄ΠΈΡ‚ количСство элСмСнтов ΠΊΠΎΠ»Π»Π΅ΠΊΡ†ΠΈΠΈ: "); int collectionLength = Int32.Parse(Console.ReadLine()); stopWatch.Start(); for (int i = 0; i < collectionLength; i++) al.Add(CreateRandomString()); foreach (var s in al) Console.Write("{0}\t", s); stopWatch.Stop(); Console.WriteLine("ВрСмя заполнСния ΠΊΠΎΠ»Π»Π΅ΠΊΡ†ΠΈΠΈ: {0}",stopWatch.ElapsedMilliseconds + " ms"); Console.WriteLine("ΠšΠΎΠ»ΠΈΡ‡Π΅ΡΡ‚Π²ΠΎ элСмСнтов Π² ΠΊΠΎΠ»Π»Π΅ΠΊΡ†ΠΈΠΈ: {0}", collectionLength); sw.Start(); al.RemoveRange(0,collectionLength); sw.Stop(); Console.WriteLine(al.Count); Console.WriteLine("ВрСмя удалСния: {0}", sw.ElapsedMilliseconds + " ms"); Console.ReadLine(); } static string CreateRandomString() { var sb = new StringBuilder(10); for (int i = 0; i < 10; i++) { var randomIndex = r.Next(chars.Length); sb.Append(chars[randomIndex]); } return sb.ToString(); 
  • How many items did you enter? - Grundy
  • 3
    Because the time to remove items is significantly less than a millisecond, of course. 2016 year in the yard. - VladD

1 answer 1

If you look at the source of ArrayList.RemoveRange , you can see the following removal process

 if (count > 0) { int i = _size; _size -= count; if (index < _size) { Array.Copy(_items, index + count, _items, index, _size - index); } while (i > _size) _items[--i] = null; _version++; } 

That is, in fact, deletion consists of simply running through all the elements and assigning null . This is a fairly quick operation in principle. Therefore, to get the removal time of more than milliseconds, you need a significant number of elements.

In addition to the ElapsedMilliseconds property, Stopwatch also has a property
ElapsedTicks β€” The total elapsed time in timer ElapsedTicks measured by the current instance.

  • Before creating a question I tried on 500,000 elements, gave 0 ms. now tried for 1,000,000 gave 1 ms) - cruim
  • @cruim, if you looked in the debugger, you could see that the value is some 0.000045 and it was simply 0.000045 when output - Grundy