1.HashTable不支持泛型,而Dictionary支持泛型。
2.Hashtable 的元素属于 Object 类型,所以在存储或检索值类型时通常发生装箱和拆箱的操作,所以你可能需要进行一些类型转换的操作,而且对于int,float这些值类型还需要进行装箱等操作,非常耗时。
3.单线程程序中推荐使用 Dictionary, 有泛型优势, 且读取速度较快, 容量利用更充分。多线程程序中推荐使用 Hashtable, 默认的 Hashtable 允许单线程写入, 多线程读取, 对 Hashtable 进一步调用 Synchronized() 方法可以获得完全线程安全的类型. 而 Dictionary 非线程安全, 必须人为使用 lock 语句进行保护, 效率大减。
关于HashTable的线程安全,微软MSDN的解释如下:
Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. To support multiple writers all operations on the Hashtable must be done through the wrapper returned by the Synchronized(Hashtable) method, provided that there are no threads reading the Hashtable object.
4.在通过代码测试的时候发现key是整数型Dictionary的效率比Hashtable快,如果key是字符串型,Dictionary的效率没有Hashtable快。
static void IntMethod() { 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(stopwatch.ElapsedMilliseconds); stopwatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { object value = hashtable[i]; } stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); } static void MethodString() { 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(),"aaa"); hashtable.Add(i.ToString(),"aaa"); } Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { string value=dictionary[i.ToString()]; } stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); stopwatch = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { object value = hashtable[i.ToString()]; } stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); }
HashTable、HashSet和Dictionary的区别(转载)
原文:https://www.cnblogs.com/OpenCoder/p/10028499.html