Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing std::unordered_map memory footprint after emptying it

Suppose I have an std::unordered_map object to which I add some elements and then remove them. Other than constructing a new object to replace the old one, is there a way to force reducing the map object's memory footprint, similar to std::vector::shrink_to_fit()?

like image 467
Danra Avatar asked Oct 17 '22 05:10

Danra


1 Answers

Since nodes are allocated and deleted as needed, the only memory that could be reduced is what is used by the bucket list. This can be done by calling rehash(0) on the unordered_map (the parameter is the minimum number of buckets to use; the actual number can be larger based on the number of things stored in the map and the max_load_factor() of the map). This is potentially a time consuming operation, depending on how many nodes end up in the same bucket.

The alternative of creating a new map will be slower, since things stored in the new map will need storage allocated for them, several rehashes may occur during all the insertions (depending on the size of the map), and the nodes used by the old map will need to be freed. Nodes could be reused by calling extract to remove nodes from the old map, and insert to add them to the new one, but rehashing in the new map could still occur.

like image 172
1201ProgramAlarm Avatar answered Oct 20 '22 20:10

1201ProgramAlarm