Remove
, vec
Elements can be added to a vector with push, but we often need to remove them later. With remove()
and swap_remove()
this is possible.
Using the swap_remove
function is often much faster, but it often disturbs the ordering of elements in the vector. So avoid it if ordering matters.
To begin we create a vector of 4 elements with the "vec
" macro. We then call remove()
to eliminate the first element—the value 10 no longer is present in the vector.
swap_remove
on the first element (index 0). This eliminates the 20, but it swaps the last element for the 20.fn main() { let mut items1 = vec![10, 20, 30, 40]; println!("{:?}", items1); // Use remove. items1.remove(0); println!("{:?}", items1); // Use swap remove. items1.swap_remove(0); println!("{:?}", items1); }[10, 20, 30, 40] [20, 30, 40] [40, 30]
Moving elements forward on each removal can be slow—a lot of memory copying must occur. Thus with swap_remove()
we can see a performance improvement.
swap_remove
instead. This changes the ordering of the elements, but it avoids copying most of them.swap_remove
function is much faster. In a real program, remove()
could cause noticeable slowdowns, but swap_remove
would be instant.use std::time::*; fn main() { if let Ok(max) = "100000".parse::<usize>() { let mut items1 = vec![100; max]; let mut items2 = items1.clone(); // Version 1: use remove. let t0 = Instant::now(); for _ in 0..max { items1.remove(0); } println!("{}", t0.elapsed().as_millis()); // Version 2: use swap remove. let t1 = Instant::now(); for _ in 0..max { items2.swap_remove(0); } println!("{}", t1.elapsed().as_millis()); println!("{}/{}", items1.len(), items2.len()); } }393 ms 0 ms (swap_remove) 0/0
With swap_remove
, we avoid shifting elements in a vector. It removes by index like the remove()
function. It is important to carefully choose the best element removal function.