本文介绍了为什么没有Dictionary.TrimExcess()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中,有一个构造词典< TKEY的,TValue> 有一个参数, INT容量。这是一样的许多其他收藏品,如名单,其中,T> 问答LT; T> 堆栈< T> ;此外,根据 MSDN文档

In .NET, there is a constructor for Dictionary<TKey, TValue> that takes one parameter, int capacity. This is the same as with many other collections such as List<T>, Queue<T>, and Stack<T>; furthermore, according to the MSDN documentation:

一个字典的容量是可以添加到词典调整是必要的前元件的数目。作为元素添加到一个词典,容量根据需要自动重新分配内部数组增加

这对我听起来pretty的大致相同,与其他收藏品一样名单,其中,T&GT; 等。由于这些集合功能自动调整大小行为,必要时和因此,可能有一个更大的容量比要求的,其中大部分都设有一个 TrimExcess 方法。这是方便的,如果,比方说,您要添加未知数量的项目到集合在同一时间,之后你会不会增加任何额外的项目。

This sounds to me pretty much the same as with other collections like List<T>, etc. Since these collections feature auto-resizing behavior when necessary and are therefore likely to have a greater capacity than required, most of them feature a TrimExcess method. This is handy if, say, you are adding an unknown number of items to the collection at one time, and after that you won't be adding any additional items.

为什么词典&LT; TKEY的,TValue&GT; 不会有同样的 TrimExcess 方法

Why does Dictionary<TKey, TValue> not have this same TrimExcess method?

(声明:我很熟悉的反应功能默认情况下不存在,我想我大多只是想知道如果有一个特别的原因 TrimExcess 词典没有意义,为什么它会显著更难实现比像列表)

(Disclaimer: I'm quite familiar with the "features do not exist by default" response; I guess I'm mostly just wondering if there's a particular reason why TrimExcess for a Dictionary does not make sense, or why it would be significantly more difficult to implement than for simpler collections like List.)

推荐答案

每MSDN字典实现为哈希表。如果你修剪多余的,你就必须拿出与该还提供了接近Ø算法(1)查询时间在什么有效地是一个随机排序的列表。

Per MSDN Dictionary is implemented as a hash table. If you trimmed excess you would have to come up with an algorithm that still provided close to O(1) lookup times in what would effectively be a randomly sorted list.

这篇关于为什么没有Dictionary.TrimExcess()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 23:52