Search code examples
c#.netdictionarytrimcapacity

Is there a way to trim a Dictionary's capacity once it is known to be fixed size?


After reading the excellent accepted answer in this question:

How is the c#/.net 3.5 dictionary implemented?

I decided to set my initial capacity to a large guess and then trim it after I read in all values. How can I do this? That is, how can I trim a Dictionary so the gc will collect the unused space later?

My goal with this is optimization. I often have large datasets and the time penalty for small datasets is acceptable. I want to avoid the overhead of reallocating and copying the data that is incured with small initial capacities on large datasets.


Solution

  • In .NET 5 there is the method TrimExcess doing exactly what you're asking:

    Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries.