Is box
just syntactic sugar or can it be applied to use cases where Box::new
is not sufficient? I read somewhere that box
is unstable, does that mean I can only use it with the nightly Rust versions?
Box::new
is just a function, like any other function. It is not special in any way whatsoever. It is grubby and smells faintly of very-close-to-the-expiration date cheese.
box
is magic and made up ground-up pixies and the dreams of little children. It is dressed in the finest, swankiest clothes and carries with it the faint aroma of freshly cut pine.
When you execute Box::new(e)
, because it is a function, e
must be completely evaluated and constructed before it can start the call. If this means allocating and filling a 500kB structure on the stack, then it has to allocate and fill a 500kB structure on the stack, and then pass that to Box::new
, which only then can allocate the space on the heap (which might fail), and then copy that 500kB into the heap.
When you execute box e
, because it is wonderful like a cool breeze on a hot summer's day, the compiler can reorder things such that it begins by allocating the 500kB on the heap, and then filling the 500kB structure directly on the heap. And then it's done. No extra copying, no chewing through stack space. No wasted effort if that "allocate on the heap" thing fails to work out.
box
is life, box
is love; all hail box
!
(And yes, as of writing, it's still unstable which means you need a nightly compiler to bask in its radiance. But soon, the dawn will come. Get it? Dawn? Nightly? ... I'll show myself out...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With