The Rust Box::new(X)
method first creates X
on the stack, then allocates memory
and copies X
from the stack to the heap. That is very wasteful if X
is large.
- Github issue: rust-lang/rust#49733
- Workaround crate: https://github.com/kvark/copyless
Simple macro that abuses vec!
to do more or less the same as the copyless
crate:
macro_rules! boxed {
($e:expr) => {{
#[inline(always)]
fn __transmute<T>(from: Box<[T]>) -> Box<T> {
unsafe { Box::from_raw(Box::into_raw(from) as *mut T) }
}
__transmute(vec![ $e ].into_boxed_slice())
}}
}
Godbolt: https://godbolt.org/z/dsYxjWMac