.NET HashTable 与字典 - 字典可以一样快吗? [英] .NET HashTable Vs Dictionary - Can the Dictionary be as fast?

查看:16
本文介绍了.NET HashTable 与字典 - 字典可以一样快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚何时以及为什么使用字典或哈希表.我在这里进行了一些搜索,发现有人在谈论我完全同意的 Dictionary 的通用优势,这导致装箱和拆箱优势略有提高.

I am trying to figure out when and why to use a Dictionary or a HashTable. I have done a bit of a search on here and have found people talking about the generic advantages of the Dictionary which I totally agree with, which leads the boxing and unboxing advantage for a slight performance gain.

但我也读过字典不会总是按照插入的顺序返回对象,它是排序的.作为 HashTable 的地方.据我了解,这会导致 HashTable 在某些情况下要快得多.

But I have also read the Dictionary will not always return the objects in the order they are inserted, thing it is sorted. Where as a HashTable will. As I understand it this leads to the HashTable being far faster for some situations.

我的问题是,这些情况可能是什么?我上面的假设是错误的吗?您可能会在哪些情况下选择一种高于另一种的情况(是的,最后一种有点模棱两可).

My question is really, what might those situations be? Am I just wrong in my assumptions above? What situations might you use to choose one above the other, (yes the last one is a bit ambiguous).

推荐答案

System.Collections.Generic.DictionarySystem.Collections.Hashtable 类两者都在内部维护一个哈希表数据结构.它们都不能保证保持项目的顺序.

System.Collections.Generic.Dictionary<TKey, TValue> and System.Collections.Hashtable classes both maintain a hash table data structure internally. None of them guarantee preserving the order of items.

撇开装箱/拆箱问题不谈,大多数情况下,它们应该具有非常相似的性能.

Leaving boxing/unboxing issues aside, most of the time, they should have very similar performance.

它们之间的主要结构差异在于Dictionary 依赖于chaining(为每个哈希表桶维护一个项目列表)来解决冲突,而Hashtable 使用 rehashing 来解决冲突(当发生冲突时,尝试另一个哈希函数将键映射到存储桶).

The primary structural difference between them is that Dictionary relies on chaining (maintaining a list of items for each hash table bucket) to resolve collisions whereas Hashtable uses rehashing for collision resolution (when a collision occurs, tries another hash function to map the key to a bucket).

如果您的目标是 .NET Framework 2.0+,使用 Hashtable 类几乎没有什么好处.Dictionary 有效地将其废弃.

There is little benefit to use Hashtable class if you are targeting for .NET Framework 2.0+. It's effectively rendered obsolete by Dictionary<TKey, TValue>.

这篇关于.NET HashTable 与字典 - 字典可以一样快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆