Skip to content

Commit 84637e6

Browse files
committed
vec::append: swap vecs instead of moving elements when the LHS is empty
1 parent 8876ffc commit 84637e6

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

library/alloc/src/vec.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1257,6 +1257,14 @@ impl<T> Vec<T> {
12571257
#[inline]
12581258
#[stable(feature = "append", since = "1.4.0")]
12591259
pub fn append(&mut self, other: &mut Self) {
1260+
// Reuses other if doing so allows us to turn a certain reallocation within self
1261+
// into a potential, future reallocation in other.
1262+
// The capacity limit ensures that we are not stealing a large preallocation from `other`
1263+
// that is not commensurate with the avoided reallocation in self.
1264+
if self.len == 0 && self.capacity() < other.len && other.capacity() / 2 <= other.len {
1265+
mem::swap(self, other);
1266+
return;
1267+
}
12601268
unsafe {
12611269
self.append_elements(other.as_slice() as _);
12621270
other.set_len(0);

0 commit comments

Comments
 (0)