Search code examples
c#performancedictionarycollectionshashtable

.NET Hashtable vs Dictionary - Can the Dictionary be as fast?


I am trying to figure out when and why to use a Dictionary or a Hashtable. I have done a bit of a search on here and have found people talking about the generic advantages of the Dictionary which I totally agree with, which leads the boxing and unboxing advantage for a slight performance gain.

But I have also read the Dictionary will not always return the objects in the order they are inserted, thing it is sorted. Where as a Hashtable will. As I understand it this leads to the Hashtable being far faster for some situations.

My question is really, what might those situations be? Am I just wrong in my assumptions above? What situations might you use to choose one above the other, (yes the last one is a bit ambiguous).


Solution

  • System.Collections.Generic.Dictionary<TKey, TValue> and System.Collections.Hashtable classes both maintain a hash table data structure internally. None of them guarantee preserving the order of items.

    Leaving boxing/unboxing issues aside, most of the time, they should have very similar performance.

    The primary structural difference between them is that Dictionary relies on chaining (maintaining a list of items for each hash table bucket) to resolve collisions whereas Hashtable uses rehashing for collision resolution (when a collision occurs, tries another hash function to map the key to a bucket).

    There is little benefit to use Hashtable class if you are targeting for .NET Framework 2.0+. It's effectively rendered obsolete by Dictionary<TKey, TValue>.