Skip to content

Commit 1396e00

Browse files
committed
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.
1 parent 90506de commit 1396e00

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
@@ -1730,7 +1730,20 @@ impl<T: Default> Default for Box<T> {
17301730
/// Creates a `Box<T>`, with the `Default` value for T.
17311731
#[inline]
17321732
fn default() -> Self {
1733-
Box::write(Box::new_uninit(), T::default())
1733+
let mut x: Box<mem::MaybeUninit<T>> = Box::new_uninit();
1734+
unsafe {
1735+
// SAFETY: `x` is valid for writing and has the same layout as `T`.
1736+
// If `T::default()` panics, dropping `x` will just deallocate the Box as `MaybeUninit<T>`
1737+
// does not have a destructor.
1738+
//
1739+
// We use `ptr::write` as `MaybeUninit::write` creates
1740+
// extra stack copies of `T` in debug mode.
1741+
//
1742+
// See https://github.com/rust-lang/rust/issues/136043 for more context.
1743+
ptr::write(&raw mut *x as *mut T, T::default());
1744+
// SAFETY: `x` was just initialized above.
1745+
x.assume_init()
1746+
}
17341747
}
17351748
}
17361749

0 commit comments

Comments
 (0)