Design considerations for choosing a collection object
I had a screening interview last week where an SDE Lead asked me what type of collection object I should be using for a given situation. Well, there was not a straight and short answer to it. But, I mentioned a few points to consider and here are they:
- Array is the fastest among all collections available in C# unless you need sort, search and dynamically extension of array size.
- ArrayList is good for storing custom object types, frequent data change, frequent insert/delete operation.
- SortedList is for fast object retrieval using an index or a key. Avoid using SortedList for large data changes
- Queue is for first in first out.
- Stack is for last in first out
- StringCollection is for storing strings.
- NameValueCollection is to store strings of key-value pairs in a presorted order.This is used for data that changes frequently where you need to insert/delete items regularly and where you need to cache items for fast retrieval.
- ListDictionary to store small amounts of data usually fewer than 10 items.
- Hashtable is used to store a large number of records and store data that may not change frequently.
- HybridDictionary is to store frequently queried data when you expect the number of records to be low with occasional increases in size.
These are the general thumb rules for choosing a collection type, but it depends on actual situation in which you need to design.