Difference between Hashtable and Dictionary

Hashtable and Dictionary are collection of data structures to hold data as key-value pairs.

Declaration

Hashtable numbers = new Hashtable();
Dictionary<int, string> dictionary = new Dictionary<int, string >();

While perform operations Dictionary is faster because there is no boxing/unboxing (valuetypes don’t need boxing) while in Hashtable boxing/unboxing (valuetypes need boxing) will happened and which may have memory consumption as well as performance penalties.

Another important difference is that Hashtable Hashtable is thread safe for supports multiple reader threads and a single writer thread. That is the Hashtable allows ONE writer together with multiple readers without locking. In the case of Dictionary there is no thread safety, if you need thread safety you must implement your own synchronization.

When we add the multiple entries in Dictionary, the order in which the entries are added is maintained. When we retrieve the items from Dictionary we will get the records in the same order we have inserted them. Whereas we add same records in Hashtable the order is not maintained. From the following example you can see the difference in the order of retrieval.

private void button1_Click(object sender, EventArgs e) { Hashtable numbers = new Hashtable(); numbers.Add(1, “one”); numbers.Add(2, “two”); numbers.Add(3, “three”); numbers.Add(4, “four”); numbers.Add(5, “five”); foreach (DictionaryEntry num in numbers) { MessageBox.Show(num.Key + ” – ” + num.Value); } Dictionary<int, string> dictionary = new Dictionary<int, string >(); dictionary.Add(1,”one”); dictionary.Add(2,”two”); dictionary.Add(3,”three”); dictionary.Add(4,”four”); dictionary.Add(5, “five”); foreach (KeyValuePair<int,string> pair in dictionary) { MessageBox.Show(pair.Key + ” – ” + pair.Value); } }

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.