In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
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 provides 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.
An additional difference is that 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 Hashtable doesn't preserve the insertion order.