What is a more efficient way to clear a Vec?

Which way is best for clearing a Vec:

let mut vec = vec![1, 24, 3, 5, 2];
vec.clear();

OR

let mut vec = vec![1, 24, 3, 5, 2];
vec = Vec::new();

Or is this dependent on what the problem is and how many elements are in the Vec?

The second one will drop the original Vec, deallocating its memory. The first one does not; the memory will remain allocated.

The first one will generally be faster, especially if you continue using the Vec after clearing it. But it may cause your program to have higher memory usage for a period of time.

1 Like
let mut vec = vec![1, 24, 3, 5, 2];
vec.clear();

this clear the vector vec ... and remove from memory

let mut vec = vec![1, 24, 3, 5, 2];
vec = Vec::new();

this replace the vector containing [1,24,3,5,2] by a new empty vector

first one is the better solution

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.