Skip to content

Commit 361898b

Browse files
committed
Auto merge of rust-lang#116568 - kornelski:hint-reserved, r=<try>
Hint optimizer about reserved capacity The fact that `Vec` had capacity increased is not known to the optimizer, because functions like `do_reserve_and_handle` are not inlined. (rust-lang#82801) Because of that, code such as: ```rust vec.try_reserve(123)?; vec.extend_from_slice(&s[..123]); ``` Tries to reserve the capacity **twice**. This is unnecessary code bloat. https://rust.godbolt.org/z/YWY16Ezej Adding a hint after reserve optimizes out the next check of `self.needs_to_grow(len, additional)`.
2 parents fee5518 + 3e1cf5b commit 361898b

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

library/alloc/src/raw_vec.rs

+5
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,11 @@ impl<T, A: Allocator> RawVec<T, A> {
292292
if self.needs_to_grow(len, additional) {
293293
do_reserve_and_handle(self, len, additional);
294294
}
295+
296+
unsafe {
297+
// Inform the optimizer that the reservation has succeeded or wasn't needed
298+
core::intrinsics::assume(!self.needs_to_grow(len, additional));
299+
}
295300
}
296301

297302
/// A specialized version of `reserve()` used only by the hot and
+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
thread 'main' panicked at library/alloc/src/raw_vec.rs:545:5:
1+
thread 'main' panicked at library/alloc/src/raw_vec.rs:550:5:
22
capacity overflow
33
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

0 commit comments

Comments
 (0)