Why is Dictionary preferred over Hashtable in C#?

后端 未结 19 1217
长情又很酷
长情又很酷 2020-11-22 05:53

In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?

19条回答
  •  囚心锁ツ
    2020-11-22 06:41

    Dictionary <<<>>> Hashtable differences:

    • Generic <<<>>> Non-Generic
    • Needs own thread synchronization <<<>>> Offers thread safe version through Synchronized() method
    • Enumerated item: KeyValuePair <<<>>> Enumerated item: DictionaryEntry
    • Newer (> .NET 2.0) <<<>>> Older (since .NET 1.0)
    • is in System.Collections.Generic <<<>>> is in System.Collections
    • Request to non-existing key throws exception <<<>>> Request to non-existing key returns null
    • potentially a bit faster for value types <<<>>> bit slower (needs boxing/unboxing) for value types

    Dictionary / Hashtable similarities:

    • Both are internally hashtables == fast access to many-item data according to key
    • Both need immutable and unique keys
    • Keys of both need own GetHashCode() method

    Similar .NET collections (candidates to use instead of Dictionary and Hashtable):

    • ConcurrentDictionary - thread safe (can be safely accessed from several threads concurrently)
    • HybridDictionary - optimized performance (for few items and also for many items)
    • OrderedDictionary - values can be accessed via int index (by order in which items were added)
    • SortedDictionary - items automatically sorted
    • StringDictionary - strongly typed and optimized for strings

提交回复
热议问题