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.
When an initializedvariable 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.