[c#] .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).

This question is related to c# .net collections dictionary hashtable

The answer is


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>.


Dictionary is faster than hashtable as dictionary is a generic strong type. Hashtable is slower as it takes object as data type which leads to boxing and unboxing.


Both are effectively the same class (you can look at the disassembly). HashTable was created first before .Net had generics. Dictionary, however is a generic class and gives you strong typing benefits. I would never use HashTable since Dictionary costs you nothing to use.


Dictionaries have the advantage of being a generic type, which makes it type safe and a bit faster due to lack of need for boxing. The following comparison table (constructed using the answers found in a similar SO question post) illustrates some of the other reasons that support dictionaries over hash tables (or vice versa).


Another important difference is that Hashtable is thread safe. Hashtable has built in multiple reader/single writer (MR/SW) thread safety which means 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.

To elaborate further:

Hashtable, provide some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections. Also, the design is not completely protected from race conditions.

The .NET Framework 2.0 collection classes like List<T>, Dictionary<TKey, TValue>, etc do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently If you need type safety as well thread safety, use concurrent collections classes in the .NET Framework. Further reading here.


Another important difference is that the Hashtable type supports lock-free multiple readers and a single writer at the same time, while Dictionary does not.


I guess it doesn't mean anything to you now. But just for reference for people stopping by

Performance Test - SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable

Memory allocation:

Memory usage performance test

Time used for inserting:

Time used for inserting

Time for searching an item:

Time for searching an item


If you care about reading that will always return the objects in the order they are inserted in a Dictionary, you may have a look at

OrderedDictionary - values can be accessed via an integer index (by order in which items were added) SortedDictionary - items are automatically sorted


Differences between Hashtable and Dictionary

Dictionary:

  • Dictionary returns error if we try to find a key which does not exist.
  • Dictionary faster than a Hashtable because there is no boxing and unboxing.
  • Dictionary is a generic type which means we can use it with any data type.

Hashtable:

  • Hashtable returns null if we try to find a key which does not exist.
  • Hashtable slower than dictionary because it requires boxing and unboxing.
  • Hashtable is not a generic type,

MSDN Article: "The Dictionary<TKey, TValue> class has the same functionality as the Hashtable class. A Dictionary<TKey, TValue> of a specific type (other than Object) has better performance than a Hashtable for value types because the elements of Hashtable are of type Object and, therefore, boxing and unboxing typically occur if storing or retrieving a value type".

Link: http://msdn.microsoft.com/en-us/library/4yh14awz(v=vs.90).aspx


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to hashtable

How do I encode a JavaScript object as JSON? Hash table runtime complexity (insert, search and delete) Looping through a hash, or using an array in PowerShell Hash function for a string hash function for string iterating through Enumeration of hastable keys throws NoSuchElementException error How do HashTables deal with collisions? Good Hash Function for Strings Iterating over and deleting from Hashtable in Java What happens when a duplicate key is put into a HashMap?