c# 当元素从哈希表中删除时,哈希表如何收缩?
我正在寻找逻辑(如果有的话),当从中删除元素时,它会缩小 c# 中的哈希表。
问候 哈里什
I am looking to find out the logic , if any , which shrinks hashtable in c# when elements are removed from it.
Regards
Harish
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C# 哈希表不收缩; 他们只会成长。 逻辑很重要,因为重新哈希算法的运行成本非常高; 在大多数情况下,重新散列到较小的散列表所节省的空间将完全被重新散列的成本所超出。 特别是在自动基础上,哈希表中的任何删除可能都不是“最后”删除(无法根据算法从哈希表中判断),潜在价值根本不值得。
如果您的哈希表显着缩小,并且您确实想回收空间,我建议您简单地创建一个新的哈希表(具有正确的大小)并将元素复制到其中。
c# hashtables don't shrink; they only grow. The logic is important, because the rehashing algorithm is VERY expensive to run; for most situations, the space saved by rehashing into a smaller hashtable would be completely overrun by the cost of the rehashing. Particularly on an automatic basis, where any removals from the hashtable may not be the "last" removal (impossible to tell from within the hashtable on an algorithmic basis), the potential value is simply not worth it.
If your hashtable shrinks significantly, and you'd really like to reclaim the space, I recommend simply creating a new one (with the right size) and copying the elements over to it.
顺便说一句,由于您使用的是 .net2.0 或更高版本,因此您可能应该使用
Dictionary
而不是 HashTable。As an aside, since you're using .net2.0 or later you should probably use a
Dictionary<K,V>
rather than a HashTable.文档中哈希表大小变化的唯一指示是当超过负载因子并且哈希表大小增加时。 没有提到急速不断缩小。
MSDN 上提供了有关负载因子的更多详细信息。
The only indication of size changes for a hashtable in the documentation is when the load factor is exceeded and the size of the hashtable is increased. There is no mention of a hastable ever shrinking.
There is some further detail of the load factor on MSDN.