Home
Rust
Vec remove, swap_remove Example
This page was last reviewed on Apr 6, 2022.
Dot Net Perls
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.
vec
Function differences. 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.
Example. 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.
Then We call swap_remove on the first element (index 0). This eliminates the 20, but it swaps the last element for the 20.
Info Swap remove avoids shifting elements forward. It instead "swaps" the last element for the one you removed.
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]
Swap benchmark. 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.
Version 1 This code uses remove on the first element in a large vector. On each removal, all remaining elements must be shifted.
Version 2 Here we call swap_remove instead. This changes the ordering of the elements, but it avoids copying most of them.
Result The 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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 6, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.