Difference Between Dictionary and Hashtable
A guy asked me the other day, what is the difference between a Dictionary and a Hashtable? I found myself stumbling a bit so I thought it would a good topic for me to write about and help me understand further. A Dictionary is a generic type Dictionary<TKey, TValue>
that allows static type which gets verified at compile-time as well as you can use a Dictionary without boxing. I am finding that using a Dictionary in .Net 2.0 and above is the preferred way to go.
A Hashtable is not a generic type and requires boxing when you are dealing with value types. A nice perk to using a Hashtable is that it allows multiple reader threads with one reader thread making a Hashtable thread safe where a Dictionary does not offer thread safety. Another difference is that in a Dictionary when you request a non-existing key an exception will be thrown. However, when you request a non-existing key in a Hashtable; a null is returned.
There is an alternative in .Net 4.0 for a Dictionary that is called ConcurrentDictionary<TKey, TValue>
.
Here is an example of a simple ConcurrentDictionary from MSDN http://msdn.microsoft.com/en-us/library/dd287191.aspx.
class CD_Ctor
{
// Demonstrates:
// ConcurrentDictionary<TKey, TValue> ctor(concurrencyLevel, initialCapacity)
// ConcurrentDictionary<TKey, TValue>[TKey]
static void Main()
{
// We know how many items we want to insert into the ConcurrentDictionary.
// So set the initial capacity to some prime number above that, to ensure that
// the ConcurrentDictionary does not need to be resized while initializing it.
int NUMITEMS = 64;
int initialCapacity = 101;
// The higher the concurrencyLevel, the higher the theoretical number of operations
// that could be performed concurrently on the ConcurrentDictionary. However, global
// operations like resizing the dictionary take longer as the concurrencyLevel rises.
// For the purposes of this example, we'll compromise at numCores * 2.
int numProcs = Environment.ProcessorCount;
int concurrencyLevel = numProcs * 2;
// Construct the dictionary with the desired concurrencyLevel and initialCapacity
ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(concurrencyLevel, initialCapacity);
// Initialize the dictionary
for (int i = 0; i < NUMITEMS; i++) cd[i] = i * i;
Console.WriteLine("The square of 23 is {0} (should be {1})", cd[23], 23 * 23);
}
}
More about….Dictionary Vs Hashtable
Richard