Memory not freed when elements of vec removed

I came across a behaviour of Vecs I don't understand. I have a shell environment (with rustyline) in which I add instances of a struct to a vec. While doing it I can monitor the amount of memory the application uses from outside and sure enough this grows as more elements are added to the vec.
However, when calling myvec.clear() followed by myvec.shrink_to_fit() I kind of expected the amount of memory used by the app to decrease again which it didn't. I assume I misunderstood something here. Will the memory taken up by this vec only be freed after it is dropped, regardless of what else I do with it or is there something I can do to reduce the amount of memory it uses but just wasn't aware of?

Memory allocators usually wont give back memory to the OS just because you deallocated it. It's more efficient to keep it around until the next time you allocate something.


You mean, there's nothing I can or should do here to try and free the memory up again?

If you want to see the number in your process viewer go down to verify to yourself that it works, you can switch to a different memory allocator and configure it to aggressively release back memory, but there's no reason to do that when just running the application — the defaults work fine in the vast vast majority of situations. The memory should get reused next time you allocate something.

1 Like

Ah yes, I just verified that when I empty the vec and then append to it again it reuses the memory until it reaches its former length. That should be fine for my use case, I was just curious why that is.

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.