Skip to content

Commit 6a83352

Browse files
committed
Introduce RawVec::reserve_for_push.
If `Vec::push`'s capacity check fails it calls `RawVec::reserve`, which then also does a capacity check. This commit introduces `reserve_for_push` which skips the redundant capacity check, for some slight compile time speed-ups. I tried lots of minor variations on this, e.g. different inlining attributes. This was the best one I could find.
1 parent 686e313 commit 6a83352

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

library/alloc/src/raw_vec.rs

+8
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,14 @@ impl<T, A: Allocator> RawVec<T, A> {
289289
}
290290
}
291291

292+
/// A specialized version of `reserve()` used only by the hot and
293+
/// oft-instantiated `Vec::push()`, which does its own capacity check.
294+
#[cfg(not(no_global_oom_handling))]
295+
#[inline(never)]
296+
pub fn reserve_for_push(&mut self, len: usize) {
297+
handle_reserve(self.grow_amortized(len, 1));
298+
}
299+
292300
/// The same as `reserve`, but returns on errors instead of panicking or aborting.
293301
pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> {
294302
if self.needs_to_grow(len, additional) {

library/alloc/src/vec/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1726,7 +1726,7 @@ impl<T, A: Allocator> Vec<T, A> {
17261726
// This will panic or abort if we would allocate > isize::MAX bytes
17271727
// or if the length increment would overflow for zero-sized types.
17281728
if self.len == self.buf.capacity() {
1729-
self.reserve(1);
1729+
self.buf.reserve_for_push(self.len);
17301730
}
17311731
unsafe {
17321732
let end = self.as_mut_ptr().add(self.len);

0 commit comments

Comments
 (0)