In .NET, there is a constructor for Dictionary
that takes one parameter, int capacity
. This is the same as with many other collecti
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.
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.
Actually I was the one that asked Microsoft to implement TrimExcess. I already presented more than one article that deals with dictionaries and in all cases I implemented TrimExcess. In fact, the Resize used when the buckets are too small can be invoked when increasing or decreasing the size of the buckets.
Today I just published another article, it is a C++ implementation of a dictionary, which supports TrimExcess: http://www.codeproject.com/Articles/761040/A-NET-like-Dictionary-in-Cplusplus
Another implementation (.NET) can be found in this article: http://www.codeproject.com/Articles/548406/Dictionary-plus-Locking-versus-ConcurrentDictionar
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.
This is partially a guess: a Dictionary is "ordered" as a hash table. The capacity that is reserved, is not simply a bunch of free memory addresses on top of your Dictionary. Instead, it consists of empty room throughout the Dictionary. This is done to make adding / moving / removing etc very efficient. If you had a TrimExcess
method for Dictionary, the whole Dictionary would have to copy everything to a new location without any gaps between the elements.
Actually: the gaps should remain otherwise the benefit of a hash table becomes void, trimming (TrimExcess
), if implemented, should only trim the internal ValueCollection
.
Update: expanded and changed my ill-chosen words
Update: the BCL team says TrimExcess for Dictionaries "could be useful".
Update: the feature request resolved as Won't Fix: "Unfortunately, we won't be able to get to this for the next release of .NET, so I'm resolving this as Won't Fix."