-
Notifications
You must be signed in to change notification settings - Fork 13.7k
Description
One would expect that the compiler would be able to avoid putting a temporary array on the stack when creating a boxed array, at least in release mode. However this doesn't seem to be the case at the moment.
Looking at this example one would expect Box::new([100;100])
to produce a similar assembly output to using the unstable box
syntax or a Vec
. The assembly output suggests that when Box::new
is used, a temporary array is created, filled in, and then an array is allocated on the heap, which and the values from the stack array are copied over with memcpy. This is obviously very suboptimal compared to the alternatives, which allocate on and write the values directly to the heap. What makes it even more confusing is that the implementation of Box::new
consists purely of the line box x
.
Now, in many situations, one could simply use Vec
since it's more flexible anyhow. A boxed array does however seem to allow the compiler to use the size information to elude bounds checks in some cases where it can't with a Vec (e.g indexing an array larger than >255 with an u8 as usize
(example). This means that it can be preferable in some situations, and the alternative would be potential slowdown, or having to use unsafe to index.