Skip to content

Commit 295768a

Browse files
committed
Performance improvement of Vec's swap_remove.
1 parent 960f604 commit 295768a

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/liballoc/vec.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -809,9 +809,13 @@ impl<T> Vec<T> {
809809
#[inline]
810810
#[stable(feature = "rust1", since = "1.0.0")]
811811
pub fn swap_remove(&mut self, index: usize) -> T {
812-
let length = self.len();
813-
self.swap(index, length - 1);
814-
self.pop().unwrap()
812+
unsafe {
813+
// We replace self[index] with the last element. Note that this is
814+
// safe even when index == self.len() - 1, as pop() only uses
815+
// ptr::read and leaves the memory at self[index] untouched.
816+
let hole: *mut T = &mut self[index];
817+
ptr::replace(hole, self.pop().unwrap())
818+
}
815819
}
816820

817821
/// Inserts an element at position `index` within the vector, shifting all

0 commit comments

Comments
 (0)