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:
The capacity of a Dictionary is the number of elements that can be added to the Dictionary before resizing is necessary. As elements are added to a Dictionary, the capacity is automatically increased as required by reallocating the internal array.
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.
Why does Dictionary<TKey, TValue>
not have this same TrimExcess
method?
(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
.)
By 2019, .Net Standard 2.1+ and .Net Core 2.1+ implement Dictionary<TKey, TValue>.TrimExcess()
:
see: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trimexcess?view=netstandard-2.1
.Net Framework doesn't implement it in any version.
I'd guess that in this case the capacity argument helps define the hashing function as well as the number of buckets; resizing/trimming a sparse collection of data would require recalculating hashes of all of the stored items remaining.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With