How to reclaim memory?

The title of this post is probably way off, sorry about that.

I have a struct that has a hashmap (HashMap<String, Vec>) that acts as a cache. Once I get everything I need I want to clear that cache out so that I don't have to worry about the memory it was taking up, but I need to keep the struct around for a much longer time.

My question is, will hashmap.clear() and hashmap.shrink_to(0) actually clear up the memory. Is there something else I should do instead or in addition?

Thanks,
Jeramy

You'll have to define "actually". In modern OSes, there is generally no good, fully reliable way to force a piece of memory to be "actually" deallocated in the sense that you can expect the free memory (as reported by whatever tool you are using) to go back up.

This isn't a problem in practice, though. You shouldn't try to outsmart the OS in the first place – allocators and the virtual memory management technique of the OS work together to accomodate most reasonable use cases.

If you need to empty the hash map, go ahead and clear() it. If you shrink_to(0), that will "free up" the remaining unused capacity as well, but that might only go so far as to marking the memory area reusable by Rust's own allocator and it may not actually give it back to the OS; this is a common optimization.

2 Likes

One easy option is just to do hashmap = HashMap::new();. Because assignment drops the left-hand side so it can move the RHS there instead, and the RHS didn't allocate.

3 Likes

In something like C# or Java doing hashmap = HashMap::new() would make the previous value an orphan and the garbage collector would eventually free it up. How does Rust handle this?

Assignment of a new value to a place drops the old value at that place (executes its destructor immediately).

5 Likes

Awesome, thanks for the help!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.