Skip to content

Commit 42e5099

Browse files
matthiaskrgrgitbot
authored and
gitbot
committed
Rollup merge of rust-lang#136089 - jwong101:box-default-debug-stack-usage, r=Amanieu
Reduce `Box::default` stack copies in debug mode The `Box::new(T::default())` implementation of `Box::default` only had two stack copies in debug mode, compared to the current version, which has four. By avoiding creating any `MaybeUninit<T>`'s and just writing `T` directly to the `Box` pointer, the stack usage in debug mode remains the same as the old version. Another option would be to mark `Box::write` as `#[inline(always)]`, and change it's implementation to to avoid calling `MaybeUninit::write` (which creates a `MaybeUninit<T>` on the stack) and to use `ptr::write` instead. Fixes: rust-lang#136043
2 parents e9bacf5 + 0d3a9c0 commit 42e5099

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

alloc/src/boxed.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -1689,7 +1689,20 @@ impl<T: Default> Default for Box<T> {
16891689
/// Creates a `Box<T>`, with the `Default` value for T.
16901690
#[inline]
16911691
fn default() -> Self {
1692-
Box::write(Box::new_uninit(), T::default())
1692+
let mut x: Box<mem::MaybeUninit<T>> = Box::new_uninit();
1693+
unsafe {
1694+
// SAFETY: `x` is valid for writing and has the same layout as `T`.
1695+
// If `T::default()` panics, dropping `x` will just deallocate the Box as `MaybeUninit<T>`
1696+
// does not have a destructor.
1697+
//
1698+
// We use `ptr::write` as `MaybeUninit::write` creates
1699+
// extra stack copies of `T` in debug mode.
1700+
//
1701+
// See https://github.com/rust-lang/rust/issues/136043 for more context.
1702+
ptr::write(&raw mut *x as *mut T, T::default());
1703+
// SAFETY: `x` was just initialized above.
1704+
x.assume_init()
1705+
}
16931706
}
16941707
}
16951708

0 commit comments

Comments
 (0)