Why is there no Dictionary.TrimExcess()?

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


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.


By 2019, .Net Standard 2.1+ and .Net Core 2.1+ implement Dictionary<TKey, TValue>.TrimExcess():

see: https://learn.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.


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.