I am new to Rust and trying to understand how boxing works. By default objects are allocated in Stack. In the follwing code the object "s" is allocated in the stack.This means the variables x and y are allocated in the stack.
struct MyStruct {
x: u64,
y: u64,
}
let s = MyStruct { //allocation in the stack ? both x and y allocated in stack?
x : 120, y: 100,
};
Now, If I Box the variable 's' , it is moved to the heap?
let boxed_s = Box::new(s); //move to heap ? copy x and y bytes to heap?
This means there is a byte-to-bye copy from stack to heap because it need to allocate and move values for x and y?
If so, isn't this causing an overhead ?
Or does the compiler do some compile-time optimization to make sure the object 's' is directly allocated in the Heap during the runtime?
It depends.
In general, if you create the instance and immediately after that wrap it in a Box
, the compiler should optimize that in a way that it directly creates the instance on the heap, without unnecessary allocations on the stack.
If you first create an instance and use it before you move it into a Box
, the above optimization would not occur. That means, the value would initially be on the stack and then moved to the heap. Technically, by "moved" I mean that internally bytes will be copied to the heap, and the old ones on the stack will not be used anymore (usually they should be released soon after, together with the other function data that will be "popped out" of the stack).