我试图弄清楚什么时候以及为什么要使用字典或哈希表。我在这里做了一些搜索,发现人们在谈论Dictionary的一般优势,我完全同意这一点,它带来了装箱和拆箱的优势,从而获得了轻微的性能增益。

但我也读过字典不会总是按照插入的顺序返回对象,事情是有序的。就像哈希表一样。据我所知,这导致哈希表在某些情况下要快得多。

我的问题是,这些情况可能是什么?我上面的假设是错的吗?你会在什么情况下选择一个而不是另一个,(是的,最后一个有点模棱两可)。


当前回答

另一个重要的区别是Hashtable是线程安全的。Hashtable内置了多读取器/单写入器(MR/SW)线程安全性,这意味着Hashtable允许一个写入器和多个读取器一起使用而不需要锁定。在Dictionary的情况下,没有线程安全,如果你需要线程安全,你必须实现自己的同步。

进一步说明:

Hashtable, provide some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections. Also, the design is not completely protected from race conditions. The .NET Framework 2.0 collection classes like List<T>, Dictionary<TKey, TValue>, etc do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently If you need type safety as well thread safety, use concurrent collections classes in the .NET Framework. Further reading here.

其他回答

我猜这对你来说已经毫无意义了。只是为了供路过的人参考

性能测试——SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable

内存分配:

插入所用时间:

项目搜索时间:

如果你关心读取,它总是按照插入到Dictionary中的顺序返回对象,你可以看看

OrderedDictionary—值可以通过整数索引访问(按添加项的顺序) SortedDictionary -项目自动排序

另一个重要的区别是Hashtable是线程安全的。Hashtable内置了多读取器/单写入器(MR/SW)线程安全性,这意味着Hashtable允许一个写入器和多个读取器一起使用而不需要锁定。在Dictionary的情况下,没有线程安全,如果你需要线程安全,你必须实现自己的同步。

进一步说明:

Hashtable, provide some thread-safety through the Synchronized property, which returns a thread-safe wrapper around the collection. The wrapper works by locking the entire collection on every add or remove operation. Therefore, each thread that is attempting to access the collection must wait for its turn to take the one lock. This is not scalable and can cause significant performance degradation for large collections. Also, the design is not completely protected from race conditions. The .NET Framework 2.0 collection classes like List<T>, Dictionary<TKey, TValue>, etc do not provide any thread synchronization; user code must provide all synchronization when items are added or removed on multiple threads concurrently If you need type safety as well thread safety, use concurrent collections classes in the .NET Framework. Further reading here.

字典比哈希表快,因为字典是泛型强类型。哈希表比较慢,因为它将对象作为数据类型,导致装箱和拆箱。

字典具有泛型类型的优点,这使得它的类型安全,而且由于不需要装箱,因此速度更快。下面的对比表(使用在类似的SO问题帖子中找到的答案构造的)说明了支持字典而不是哈希表的其他一些原因(反之亦然)。