共同点:
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);
}