.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?
Off the top of my head:
Array
* - represents an old-school memory array - kind of like a alias for a normaltype[]
array. Can enumerate. Can't grow automatically. I would assume very fast insert and retrival speed.ArrayList
- automatically growing array. Adds more overhead. Can enum., probably slower than a normal array but still pretty fast. These are used a lot in .NETList
- one of my favs - can be used with generics, so you can have a strongly typed array, e.g.List<string>
. Other than that, acts very much likeArrayList
Hashtable
- plain old hashtable. O(1) to O(n) worst case. Can enumerate the value and keys properties, and do key/val pairsDictionary
- same as above only strongly typed via generics, such asDictionary<string, string>
SortedList
- a sorted generic list. Slowed on insertion since it has to figure out where to put things. Can enum., probably the same on retrieval since it doesn't have to resort, but deletion will be slower than a plain old list.
I tend to use List
and Dictionary
all the time - once you start using them strongly typed with generics, its really hard to go back to the standard non-generic ones.
There are lots of other data structures too - there's KeyValuePair
which you can use to do some interesting things, there's a SortedDictionary
which can be useful as well.
If at all possible, use generics. This includes:
- List instead of ArrayList
- Dictionary instead of HashTable
First, all collections in .NET implement IEnumerable.
Second, a lot of the collections are duplicates because generics were added in version 2.0 of the framework.
So, although the generic collections likely add features, for the most part:
- List is a generic implementation of ArrayList.
- Dictionary is a generic implementation of Hashtable
Arrays are a fixed size collection that you can change the value stored at a given index.
SortedDictionary is an IDictionary that is sorted based on the keys. SortedList is an IDictionary that is sorted based on a required IComparer.
So, the IDictionary implementations (those supporting KeyValuePairs) are: * Hashtable * Dictionary * SortedList * SortedDictionary
Another collection that was added in .NET 3.5 is the Hashset. It is a collection that supports set operations.
Also, the LinkedList is a standard linked-list implementation (the List is an array-list for faster retrieval).