1. 程式人生 > >個人對 HashTable 和 Dictionary的區別總結

個人對 HashTable 和 Dictionary的區別總結

共同點:
Dictionary 是 HashTable 的一個特殊衍生類(並不是子類,僅相似)
1、內建都是HashTable類。
2、都需要immutable(不變的)且 unique(唯一的)的鍵key
3、二者的鍵都需要自己的GetHashCode() 方法

HashTable:
優:
HashTable  --> 
1、插入的鍵值對可以是任意型別,這在 HashTable 定義時不用去宣告他所要容納的型別。你可以這樣插入任意 Object 型別的鍵和值,注意是 “任意型別”,非常強大。
2、HashTable 在查詢時,如果試圖 利用鍵 查詢一個不存在 鍵值時,它會返回null。它不會丟擲異常
3、支援 多路讀線且單路寫線的執行緒安全。

劣:
1、HashTable在進行根據 鍵值 進行插入時,得出想要插入的位置,如果位置衝突,則會通過一定的演算法不停的尋找下一個空的可插入的點(在HashTable內資料已經很多的時候,衝突會經常造成,這就耗去了大量的時間去找插入點),並且由於其  任意型別鍵值 的原因,HashTable 在插入 與取出的過程中,需要分別對鍵值進行Boxing 和 Unboxing ,這同樣有一定的開銷。


2、優點即是缺點,HashTable 因為是任意型別,這就導致 type safety(型別安全)問題,其中的資料是 Object 型別的,你就需要對其中的鍵值進行型別判斷,可能由於人記憶力問題或資料誤操作,造成非常隱晦的bug,為開發造成不必要的麻煩。

HashTable  ht = new HashTable();
ht.Add("tom",customer);
ht.Add(2.3,"HashTable");

Customer customer = ht["tom"] as Customer;


Dictionary:
優:
1、Type safety(型別安全):在定義的時候就必須指定鍵值型別,the key type and value type is geniric(普通)type,(相較於Object的全家桶而言)

Dictionary dict = new Dictionary<string, Customer >();
Customer customer = dict["tom"];
2、訪問的速度更快,本身不用打包(boxing)和解包(unboxing),速度稍稍稍微快了一點

劣:
1、如果試圖訪問不存在的鍵值對,直接throw Access Exception(訪問異常)
2、不支援執行緒安全,如果需要實現執行緒安全的字典,那麼可以使用 .NET 框架的ConcurrentDictionary<TKey,TValue>,(可能還需自己同步化?).

關於二者的一些使用 實驗資料分析如下:
1、HashTable 大資料量插入資料時需要花費比Dictionary 大得多的時間
2、三種遍歷方式中(for / foreach / GetEnumerator)中,for方式遍歷HashTable 和Dictionary速度最快
3、用foreach方式遍歷時Dictionary遍歷速度更快。
 

PS. 其實只有Dictionary(字典)內資料叫做  KeyValuePair(鍵值對) <--> 而HashTable內資料叫做 DictionaryEntry(字典條目?),以上為方便均稱為鍵值對,希望不要引起誤解。

最後:引用一下幾個國外大佬的總結:

http://stackoverflow.com/questions/301371/why-is-dictionary-preferred-over-hashtable
1.

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
2、
http://stackoverflow.com/questions/876656/difference-between-dictionary-and-hashtable

A subtle but important difference is that Hashtable supports multiple reader threads 
with a single writer thread, while Dictionary offers no thread safety. If you need 
thread safety with a generic dictionary, you must implement your own synchronization or 
(in .NET 4.0) use ConcurrentDictionary<TKey, TValue>.

最後,貼一些程式碼以便借鑑使用:


Dictionary<string, int> dictionary = new Dictionary<string, int>();
    dictionary.Add("cat", 2);
    dictionary.Add("dog", 1);
    dictionary.Add("llama", 0);
    dictionary.Add("iguana", -1);

    //dictionary.Add(1, -2); // Compilation Error


    foreach (KeyValuePair<string, int> pair in dictionary)
    {
        lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
    }
  }

對HashTable:


foreach (DictionaryEntry item in myHash)
{
        Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
}