What do Box<T>, Vec<T>, Rc<T> and Box<dyn Trait> look like in memory?
On 64-bit, Box<T> is one 8-byte pointer to the heap value. Vec<T> is 24 bytes: pointer, capacity, length. Rc<T>/Arc<T> are 8, with both counts in the heap block beside the value. Box<dyn Trait> is 16: data and vtable pointers.
- Thinking the size of
Box<T>grows withT, when only unsized targets likestrordyn Traitmake it 16 - Placing the
Rccounts next to the pointer on the stack instead of in the heap block - Expecting
Box<dyn Trait>to be one word, forgetting the vtable pointer of a fat pointer
- Why does
Option<Box<T>>take 8 bytes and not 16? - What does
size_of::<Rc<str>>()report, and why?
size_of reports the size of what sits on the stack; everything else is on the heap. Checked on a 64-bit target:
use std::fmt::Display;
use std::mem::size_of;
use std::rc::Rc;
use std::sync::Arc;
fn main() {
println!("{}", size_of::<Box<i32>>()); // 8
println!("{}", size_of::<Box<[u8; 4096]>>()); // 8
println!("{}", size_of::<Vec<i32>>()); // 24
println!("{}", size_of::<Rc<i32>>()); // 8
println!("{}", size_of::<Arc<i32>>()); // 8
println!("{}", size_of::<Box<dyn Display>>()); // 16
println!("{}", size_of::<Option<Box<i32>>>()); // 8
println!("{}", size_of::<Rc<str>>()); // 16
}A Box<T> for a sized type is a bare address, however much the value weighs. A Vec<T> holds a pointer to its buffer, the capacity and the length; the language promises the set of fields, not their order. Rc<T> and Arc<T> are one address too, but it leads to a block where the strong and weak counts sit before the value (atomic ones for Arc), so Rc::new(5) allocates 24 bytes on the heap, not 4.
A pointer to an unsized type is fat: the address gets a length (Box<str>, Rc<str>, &[T]) or a pointer to the vtable (Box<dyn Trait>). There is one vtable per type–trait pair, in the program's static memory, not one per value. Option<Box<T>> stays 8 bytes because a Box is never null, so None is encoded as the null address — the same niche optimization works for Option<Rc<T>> and Option<&T>.