I want to do a performance test on how fast an ArrayList(System.Collections – C#) can insert an item at the beginning.
I’ve opened a file for reading lines of data from, set up a Stopwatch and also created an ArrayList to add items to(as follows):
Stopwatch watchTime = new Stopwatch();
Double totalTime = 0;
using (StreamReader readText = new StreamReader("data.txt"))
{
String line;
Int32 counter = 0;
while ((line = readText.ReadLine()) != null)
{
}
}
I use the counter to keep track of how many items i’m entering into the ArrayList.
Within the while loop i have the following:
watchTime.Start();
theList.Insert(0, line);
watchTime.Stop();
Double time = watchTime.Elapsed.TotalMilliseconds;
totalTime = totalTime + time;
Console.WriteLine(time);
watchTime.Reset();
++counter;
Is this a correct way of checking how fast inserting items into the beginning of the ArrayList occurs??
I made another program that does the exact same thing – however using a Dictionary. To my surprise, the time it takes for this ArrayList to insert items is much longer than the amount of time the Dictionary takes. Why is this happening?
Well, I would suggest:
ArrayListwithout doing anything else. Time that big loop in one go.As for why
Dictionary<,>is cheaper – you didn’t show any code, but basically your insertion code will have to copy the entire contents of theArrayListon every insertion.ArrayListmaintains an array to hold the contents of the list. Usually the array is larger than the list – when you add an element at the end, if can just assign the new value into the right bit of the array. If you insert it elsewhere, it has to copy elements of the array to “make room” for the new element.You’d find it a lot quicker adding at the end.
Dictionary<,>uses a completely different data structure; it has to resize at some points, but it will have very different characteristics in general.(I would suggest you use
List<T>instead ofArrayListto start with, and if you want a collection you can insert at the start of repeatedly, consider aLinkedList<T>– or possibly a queue or stack, depending on what you want to do with it later.)