Why is there no Dictionary.TrimExcess()?

后端 未结 5 1517
醉梦人生
醉梦人生 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: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."

提交回复
热议问题