Collections In C# .Net
3 Types of collection types are supported in C# : ArrayList, Hashtable, SortedList
ArrayList can contain different types of object while Hashtable can not.For searching data in collection,
ArrayList is slower as it searches in all fields while Hashtable searches only for key.
Have You Considered Strongly Typed Collections?
You should prefer StringCollection over ArrayList when storing strings. This avoids casting overhead that occurs when you insert or retrieve items and also ensures that type checking occurs. You can develop a custom collection for your own data type. For example, you could create a Cart collection to store objects of type CartItem.
Do You Use ArrayList?
If your code uses ArrayList, review the following questions:
- Do you store strongly typed data in ArrayLists?
Use ArrayList to store custom object types, particularly when the data changes frequently and you perform frequent insert and delete operations. By doing so, you avoid the boxing overhead. The following code fragment demonstrates the boxing issue.
ArrayList al = new ArrayList();
al.Add(42.0F); // Implicit boxing because the Add method takes an object
float f = (float)al[0]; // Item is unboxed here - Do you use Contains to search ArrayLists?
Store presorted data and use ArrayList.BinarySearch for efficient searches. Sorting and linear searches using Contains are inefficient. This is of particular significance for large lists. If you only have a few items in the list, the overhead is insignificant. If you need several lookups/search, then consider Hashtable instead of ArrayList.
Do You Use Hashtable?
If your code uses a Hashtable collection of key/value pairs, consider the following review questions:
- Do you store small amounts of data in a Hashtable?
If you store small amounts of data (10 or fewer items), this is likely to be slower than using a ListDictionary. If you do not know the number of items to be stored, use a HybridDictionary.
- Do you store strings?
Prefer StringDictionary instead of Hashtable for storing strings, because this preserves the string type and avoids the cost casting .
Do You Use SortedList?
You should use a SortedList to store key-and-value pairs that are sorted by the keys and accessed by key and by index. New items are inserted in sorted order, so the SortedList is well suited for retrieving stored ranges.
You should use SortedList if you need frequent re-sorting of data after small inserts or updates. If you need to perform a number of additions or updates and then re-sort the whole collection, an ArrayList performs better than the SortedList.
Evaluate both collection types by conducting small tests and measuring the overall overhead in terms of time taken for sorting, and choose the one which is right for your scenario.
0 Comments:
Post a Comment
<< Home