Why is there no Dictionary.TrimExcess()?

后端 未结 5 1525
醉梦人生
醉梦人生 2021-02-14 08:03

In .NET, there is a constructor for Dictionary that takes one parameter, int capacity. This is the same as with many other collecti

相关标签:
5条回答
  • 2021-02-14 08:13

    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.

    0 讨论(0)
  • 2021-02-14 08:15

    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.

    0 讨论(0)
  • 2021-02-14 08:15

    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

    0 讨论(0)
  • 2021-02-14 08:16

    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.

    0 讨论(0)
  • 2021-02-14 08:23

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

    0 讨论(0)
提交回复
热议问题