Skip to content

Commit f99f9e4

Browse files
committed
Auto merge of #98755 - nnethercote:faster-vec-insert, r=cuviper
Optimize `Vec::insert` for the case where `index == len`. By skipping the call to `copy` with a zero length. This makes it closer to `push`. I did this recently for `SmallVec` (servo/rust-smallvec#282) and it was a big perf win in one case. Although I don't have a specific use case in mind, it seems worth doing it for `Vec` as well. Things to note: - In the `index < len` case, the number of conditions checked is unchanged. - In the `index == len` case, the number of conditions checked increases by one, but the more expensive zero-length copy is avoided. - In the `index > len` case the code now reserves space for the extra element before panicking. This seems like an unimportant change. r? `@cuviper`
2 parents ada8c80 + 679c5ee commit f99f9e4

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

library/alloc/src/vec/mod.rs

+9-6
Original file line numberDiff line numberDiff line change
@@ -1379,9 +1379,6 @@ impl<T, A: Allocator> Vec<T, A> {
13791379
}
13801380

13811381
let len = self.len();
1382-
if index > len {
1383-
assert_failed(index, len);
1384-
}
13851382

13861383
// space for the new element
13871384
if len == self.buf.capacity() {
@@ -1393,9 +1390,15 @@ impl<T, A: Allocator> Vec<T, A> {
13931390
// The spot to put the new value
13941391
{
13951392
let p = self.as_mut_ptr().add(index);
1396-
// Shift everything over to make space. (Duplicating the
1397-
// `index`th element into two consecutive places.)
1398-
ptr::copy(p, p.offset(1), len - index);
1393+
if index < len {
1394+
// Shift everything over to make space. (Duplicating the
1395+
// `index`th element into two consecutive places.)
1396+
ptr::copy(p, p.offset(1), len - index);
1397+
} else if index == len {
1398+
// No elements need shifting.
1399+
} else {
1400+
assert_failed(index, len);
1401+
}
13991402
// Write it in, overwriting the first copy of the `index`th
14001403
// element.
14011404
ptr::write(p, element);

0 commit comments

Comments
 (0)