Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no Dictionary.TrimExcess()?

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

like image 219
Dan Tao Avatar asked Oct 26 '09 14:10

Dan Tao


2 Answers

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.

like image 55
Jaime Avatar answered Sep 26 '22 23:09

Jaime


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.

like image 37
Joe Avatar answered Sep 24 '22 23:09

Joe