Dictionary和Hashtable 是兩個比較常用的表示鍵/值的集合,兩者在實際使用過程中有何區別呢?
具體區別如下:
1. Hashtable不支持泛型,而Dictionary支持泛型。
2. Hashtable中的元素值為Object類型,所以在存儲或檢索值類型時通常會發生裝箱和拆箱的操作,非常耗時。
3. 單線程中推薦使用Dictionary,有泛型優勢。多線程中推薦使用Hashtable,默認的Hashtable允許單線程寫入,多線程讀取,對Hashtable進一步調用Synchronized()方法可以獲得完全線程安全的類型,而Dictionary非線程安全,必須人為使用lock語句進行保護,效率大減。
4. 在通過代碼測試的時候發現key是整數型Dictionary的效率比Hashtable快,如果key是字符串型,Dictionary的效率沒有Hashtable快。

/// <summary> /// key為整型,Dictionary和Hashtable效率比較 /// </summary> static void IntMethod() { Console.WriteLine("Key為整型,Dictionary和Hashtable查詢性能比較:"); int count = 1000000; Dictionary<int, int> dictionary = new Dictionary<int, int>(); Hashtable hashtable = new Hashtable(); for (int i = 0; i < count; i++) { dictionary.Add(i, i); hashtable.Add(i, i); } Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { int value = dictionary[i]; } stopwatch.Stop(); Console.WriteLine("Dictionary:" + stopwatch.ElapsedMilliseconds); stopwatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { object value = hashtable[i]; } stopwatch.Stop(); Console.WriteLine("Hashtable:" + stopwatch.ElapsedMilliseconds); }

/// <summary> /// Key為字符型,Dictionary和Hashtable查詢性能比較 /// </summary> static void StringMethod() { Console.WriteLine("Key為字符型,Dictionary和Hashtable查詢性能比較:"); int count = 1000000; Dictionary<string, string> dictionary = new Dictionary<string, string>(); Hashtable hashtable = new Hashtable(); for (int i = 0; i < count; i++) { dictionary.Add(i.ToString(), "String"); hashtable.Add(i, i); } Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { string value = dictionary[i.ToString()]; } stopwatch.Stop(); Console.WriteLine("Dictionary:" + stopwatch.ElapsedMilliseconds); stopwatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { object value = hashtable[i.ToString()]; } stopwatch.Stop(); Console.WriteLine("Hashtable:" + stopwatch.ElapsedMilliseconds); }
結果如下:
參考: