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
.)