Sunday 2 October 2011

Some performance issues when woring with collectins


The main purpose of collections is to deal with a large number of items, and as the number of items increased the performance of your application will be affected. To reduce the effect of the number of items on your application you have to choose the right kind of collection you will use. This depends on the usage patterns that are expected from your collection. You have to decide whether you will insert all the items in the collection only on initialization of your application, or you will do that through out the life time of the application. How many times will you need to iterate through the items of the collection. Will you need to insert new items at the middle, or just add the new ones to the end of the collection. Is it important to store your items in order or not, and so on. You have to decide what is the key operation you need; is it iteration?, insertion, lookup, or saving data in order. You can choose the right collection depending on the usage pattern of data.
For example when your main concern is lookups and you don't mind about the order of items, your first choice should be System.Collections.Generic.Dictionary. that has a very fast lookups plus quick additions and removals. The mentioned three operations operate quickly even if the collection contains millions of items.
Dim Dic As New System.Collections.Generic.Dictionary_
    (Of Integer, String)
Dic.Add(12, "Aa")
Dic.Add(20, "Bb")
Dic.Add(100, "Cc")
Dim s As String = Dic.Item(20)
Dic.Remove(100)
If your usage is mostly addition and a few deletions, and if it is important for the logic of your program to keep items in order you will need to use the System.Collections.Generic.List collection. In this situation lookup will be slow because the need to traverse the entire list items to get the required one. Inserting items at the middle of the collection or removing existing items will take a valuable amount of time too, but adding items at the end will be very quick.
Dim L As New System.Collections.Generic.List(Of String)
L.Add("Aa")
L.Add("Bb")
L.Add("Dd")
L.Insert(2, "Cc")
L.Remove("Bb")
This tutorial is written by ThinkAndCare.

No comments:

Post a Comment