Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 529
philologon Avatar asked Mar 15 '14 20:03

philologon


Video Answer


1 Answers

According to Reflector, the Dictionary class never shrinks. void Resize() is hard-coded to always double the size.

You can probably create a new dictionary and use the respective constructor to copy over the items. This will be quite inefficient.

Or, implement your own dictionary with the existing one as a blue-print. This is less work than you might think at first.

Be sure to benchmark both approaches.

like image 116
usr Avatar answered Nov 15 '22 01:11

usr