Skip to content

Commit bbcb772

Browse files
Specialize Vec::extend_with for T: Copy
After running perf on the previous commit, it was found that the compile-time regression was too significant to ignore. This introduces a specialized, simplified implementation for `T: Copy` that will contain the perf regression.
1 parent 595a8d2 commit bbcb772

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,12 @@ use self::spec_extend::SpecExtend;
150150
#[cfg(not(no_global_oom_handling))]
151151
mod spec_extend;
152152

153+
#[cfg(not(no_global_oom_handling))]
154+
use self::spec_extend_with::SpecExtendWith;
155+
156+
#[cfg(not(no_global_oom_handling))]
157+
mod spec_extend_with;
158+
153159
/// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
154160
///
155161
/// # Examples
@@ -3258,7 +3264,7 @@ impl<T: Clone, A: Allocator> Vec<T, A> {
32583264
#[track_caller]
32593265
/// Extend the vector by `n` clones of value.
32603266
fn extend_with(&mut self, n: usize, value: T) {
3261-
self.extend_trusted(iter::repeat_n(value, n));
3267+
<Self as SpecExtendWith<T>>::spec_extend_with(self, n, value);
32623268
}
32633269
}
32643270

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
use core::iter;
2+
use core::mem::MaybeUninit;
3+
4+
use super::Vec;
5+
use crate::alloc::Allocator;
6+
7+
// Specialization trait used for Vec::extend_with
8+
pub(super) trait SpecExtendWith<T> {
9+
#[track_caller]
10+
fn spec_extend_with(&mut self, n: usize, value: T);
11+
}
12+
13+
impl<T: Clone, A: Allocator> SpecExtendWith<T> for Vec<T, A> {
14+
#[track_caller]
15+
default fn spec_extend_with(&mut self, n: usize, value: T) {
16+
self.extend_trusted(iter::repeat_n(value, n));
17+
}
18+
}
19+
20+
impl<T: Copy, A: Allocator> SpecExtendWith<T> for Vec<T, A> {
21+
#[track_caller]
22+
fn spec_extend_with(&mut self, n: usize, value: T) {
23+
let len = self.len();
24+
self.reserve(n);
25+
let unfilled = self.spare_capacity_mut();
26+
27+
// SAFETY: the above `reserve` call guarantees `n` to be in bounds.
28+
let unfilled = unsafe { unfilled.get_unchecked_mut(..n) };
29+
for elem in unfilled {
30+
*elem = MaybeUninit::new(value);
31+
}
32+
33+
// SAFETY: the elements have been initialized above.
34+
unsafe { self.set_len(len + n) }
35+
}
36+
}

0 commit comments

Comments
 (0)