Is there a way to crop the dictionary capacity as soon as it is known as a fixed size?

Having read the excellent answer in this question:

How is the C # /. NET 3.5 dictionary implemented?

I decided to set my initial capacity to a big guess, and then cut it off after I read all the values. How can i do this? That is, how can I crop a dictionary so that gc collects unused space later?

My goal is optimization. I often have large data sets and allow a time penalty for small data sets. I want to avoid the overhead of redistributing and copying data that was taken with small initial capacities in large data sets.

+4
source share
2 answers

According to Reflector, the Dictionary class is never compressed. void Resize()hardcoded to always double the size.

Perhaps you can create a new dictionary and use the appropriate constructor to copy elements. It will be quite inefficient.

Or, implement your own vocabulary with an existing blue print. This works less than you might think at first.

Be sure to compare both approaches.

+2
source

You can first put your data in a list. Then you know the size of the list and you can create a dictionary with such capacity (now for the exact data you need) and fill it.

( ) , . (, , !) , , GetHashCode , . , .

+1

Source: https://habr.com/ru/post/1531964/