What is the best way to clean the memory taken by Vec?

Hi everyone !

Could somebody explain what is the best way to clean the memory taken by Vec ?

I used such code to test a memory usage:

use std::mem;

fn main() {
    let mut vector: Vec<i32> = vec![1, 2, 3, 4];
    // first method: uncomment two lines below
    // vector.clear();
    // vector.shrink_to_fit();

    // second method: not sure if I should use drop(vector) before
    vector = vec![];
    
    println!("{:?}", vector);
    
    let size = memory_size_of_vec(&vector);
    println!("Memory usage: {} bytes", size);
}

fn memory_size_of_vec<T>(vec: &Vec<T>) -> usize {
    vec.capacity() * mem::size_of::<T>()
}

after first method (combo of clear and shrink_to_fit) and second method (just reassignment) memory_size_of_vec function shows me 0 bytes. So from my point of view reassignment is better because I do less actions.

Both achieve the same thing and most likely optimize down to the same code, but reassignment is technically simpler and most straightforward.

4 Likes

No, you don't need to explicitly drop it, the old value will be dropped automatically by the assignment.

https://doc.rust-lang.org/reference/destructors.html

When an initialized variable or temporary goes out of scope, its destructor is run, or it is dropped. Assignment also runs the destructor of its left-hand operand, if it’s initialized. If a variable has been partially initialized, only its initialized fields are dropped.

1 Like

Yes; I would say that shrink_to_fit is more for the situation when you keep some values, but still want to shrink the extra capacity.

For example, it might be useful after a .retain(…) that you expect to remove nearly all the elements.

I agree with kornel that if you want to remove all the elements and all the capacity, might as well just use the assignment.

2 Likes