Hashtable vs Generic Dictionary : Performance Comparison
The Generic Dictionary<TKey,TValue> was introduced in .Net 2.0 as a replacement for the Hashtable. However, the implementation and behavior of the generic Dictionary is not exactly the same as a Hashtable, and it always bothered me. I felt that the generic Dictionary was not going to be as fast and efficient as a raw Hashtable. When speed was the utmost concern, I chose to use a Hashtable despite the lack of strongly typed Key and Value. And it kept bothering me, why was a different implementation chosen for the Dictionary, why not just wrapping around a Hashtable?
So finally I took the time to write some test code and compare the speed of Dictionary vs Hashtable. To my surprise, the Dictionary is faster! It is not only faster than the Hashtable, but also more consistent in the lookup times compared to a Hashtable. My focus here is look-up time, no comparison was done for the time it takes to add items.
Without going into the details, I will just outline the test setup:
A set of about 16,000 objects were added to a Hashtable and a Dictionary, with string of various length as the Key. Time was clocked for 50,000 lookups with the same Key from both Dictionary and Hashtable. This process was repeated with Keys of different length, as well as for items towards the beginning, middle and end of the list. In all cases, the Dictionary showed better performance (speed). Depending on the size of the key, and to which end of the list that item was located, the difference in speed varied, but I was able to clock anywhere between 10% to 40% faster lookups on the Dictionary.
Also, as I mentioned before, besides being faster, the Dictionary showed more consistent result while the Hashtable's speed varied over multiple runs. Don't ask me why.
Bottom line, there is no reason not to use the Dictionary over the concern of speed. Now I know.
Posted on January 15, 2010 05:03 by
Haider