Trait Objects & Dynamic Dispatch
Rust gives you two flavours of trait dispatch: static (monomorphisation) and dynamic (trait objects). We'll dissect both at the assembly level, take fat pointers apart, and put real numbers on the performance gap.
Static Dispatch (Monomorphisation)
Hand the compiler a generic with trait bounds and it stamps out a fresh copy for every concrete type that walks through:
trait Area { fn area(&self) -> f64;}
struct Circle { radius: f64 }struct Square { side: f64 }
impl Area for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.radius * self.radius }}
impl Area for Square { fn area(&self) -> f64 { self.side * self.side }}
fn print_area<T: Area>(shape: &T) { println!("Area: {}", shape.area());}
fn main() { let c = Circle { radius: 5.0 }; let s = Square { side: 3.0 }; print_area(&c); print_area(&s);}The compiler generates two separate functions:
; print_area::<Circle>; Specialized for Circle - calls Circle::area directlyprint_area_circle: ; Load radius from the Circle struct movsd xmm0, QWORD PTR [rdi] ; self.radius mulsd xmm0, xmm0 ; radius * radius mulsd xmm0, QWORD PTR [rip+PI] ; * PI ; ... format and print ... ret
; print_area::<Square>; Specialized for Square - calls Square::area directlyprint_area_square: movsd xmm0, QWORD PTR [rdi] ; self.side mulsd xmm0, xmm0 ; side * side ; ... format and print ... retEach instantiation has the area() call inlined right in. No indirection, no vtable, no runtime cost. The compiler sees the concrete type at every call site and tailors the code accordingly.
Dynamic Dispatch (Trait Objects)
Reach for dyn Trait and you've thrown away the concrete type. The compiler now has to work blind:
fn print_area_dynamic(shape: &dyn Area) { println!("Area: {}", shape.area());}
fn main() { let shapes: Vec<Box<dyn Area>> = vec![ Box::new(Circle { radius: 5.0 }), Box::new(Square { side: 3.0 }), ]; for shape in &shapes { print_area_dynamic(shape.as_ref()); }}print_area_dynamic: ; rdi = data pointer (pointer to the actual struct) ; rsi = vtable pointer (pointer to the trait's vtable for this type) mov rax, QWORD PTR [rsi+24] ; Load area() function pointer from vtable call rax ; Indirect call ; ... format and print ... retFat Pointers
A &dyn Trait is a fat pointer — two 8-byte words shoved into one reference:
The data pointer aims at the underlying struct. The vtable pointer aims at a static table of function pointers — same idea as a C++ vtable, but kept apart from the object instead of welded into the front of it.
Rust vtables vs C++ vtables
The key structural difference:
C++ vtable: Embedded in the object (vtable pointer is the first field of every polymorphic object).
The upshot: Rust objects without dyn carry zero vtable overhead. A Circle is 8 bytes — one f64, full stop. In C++, the moment that class picks up a single virtual method, every instance balloons by an extra pointer.
The Cost of dyn Trait
Put both styles in a tight loop and watch what happens:
// Static dispatch: monomorphizedfn sum_areas_static(shapes: &[Circle]) -> f64 { shapes.iter().map(|s| s.area()).sum()}
// Dynamic dispatch: trait objectsfn sum_areas_dynamic(shapes: &[&dyn Area]) -> f64 { shapes.iter().map(|s| s.area()).sum()}Static dispatch assembly:
sum_areas_static: ; The loop body is fully inlined: movsd xmm1, QWORD PTR [rdi] ; Load radius mulsd xmm1, xmm1 ; radius^2 mulsd xmm1, QWORD PTR [rip+PI] ; * PI addsd xmm0, xmm1 ; sum += area add rdi, 8 ; Next circle dec rcx jnz .loopDynamic dispatch assembly (simplified by hand, not exact rustc output):
sum_areas_dynamic: ; rbx = current fat pointer, r12 = items left. Both are callee-saved, ; so they survive the call. Every xmm register is caller-saved, so the ; running sum lives on the stack at [rsp] across the call..loop: mov rdi, QWORD PTR [rbx] ; Data pointer (self) from the fat pointer mov rax, QWORD PTR [rbx+8] ; Vtable pointer call QWORD PTR [rax+24] ; area(): slot after drop, size, align addsd xmm0, QWORD PTR [rsp] ; Result comes back in xmm0; add the sum movsd QWORD PTR [rsp], xmm0 ; Store the new sum add rbx, 16 ; Next fat pointer (16 bytes each) dec r12 jnz .loopThe dynamic version has:
- Three dependent loads before it can call anything (data pointer, vtable pointer, function pointer)
- An indirect call instead of inlined code, which also forces the running sum out to memory and back on every iteration
- 16-byte fat pointers instead of 8-byte data
Step through that loop over a Circle and a Square. Watch each fat pointer give up its data half to rdi and its vtable half to rax, then open the comparison underneath to see the monomorphised loop, which never calls anything.
Looping over Vec<Box<dyn Area>>
Each element is a 16-byte fat pointer: a data pointer and a vtable pointer. Step through the loop and watch both words get used. Addresses are illustrative, and rustc's vtable layout is an implementation detail.
rbx points at the Vec's buffer of 2 Box<dyn Area> fat pointers, 16 bytes each. The running sum starts at 0.0 on the stack.
x86-64 (Intel syntax)
- .loop: ; rbx = current fat pointer, r12 = items left
- mov rdi, QWORD PTR [rbx] ; data pointer (self)
- mov rax, QWORD PTR [rbx+8] ; vtable pointer
- call QWORD PTR [rax+24] ; area(): slot after drop, size, align
- addsd xmm0, QWORD PTR [rsp] ; add the running sum
- movsd QWORD PTR [rsp], xmm0 ; store the new sum
- add rbx, 16 ; next fat pointer
- dec r12
- jnz .loop
Registers
- rbx
- 0x4052a0
- r12
- 2
- rdi
- -
- rax
- -
- xmm0
- -
- [rsp]
- 0.0
- target
- -
Vec buffer at 0x4052a0: Box<dyn Area> × 2
| +0 | [0] data | 0x4052c0 → Circle |
| +8 | [0] vtable | 0x404d20 → Circle vtable |
| +16 | [1] data | 0x4052e0 → Square |
| +24 | [1] vtable | 0x404d40 → Square vtable |
Circle on the heap at 0x4052c0 (8 bytes, no vptr)
| +0 | radius: f64 | 5.0 |
Square on the heap at 0x4052e0 (8 bytes, no vptr)
| +0 | side: f64 | 3.0 |
Stack
[rsp] sum = 0.0
vtable for Circle as Area at 0x404d20
| +0 | drop_in_place | drop_in_place::<Circle> |
| +8 | size | 8 |
| +16 | align | 8 |
| +24 | area | <Circle as Area>::area |
vtable for Square as Area at 0x404d40
| +0 | drop_in_place | drop_in_place::<Square> |
| +8 | size | 8 |
| +16 | align | 8 |
| +24 | area | <Square as Area>::area |
The drop entry runs the type's destructor when a Box is freed; size and align tell the allocator how much to free. Types that need no drop glue may get a no-op or null entry.
Compare: the monomorphised loop over &[Circle]
With the type known at compile time there's no fat pointer, no vtable and no call. The area is inlined and the sum stays in xmm0 the whole time.
- .loop: ; sum_areas_static(&[Circle])
- movsd xmm1, QWORD PTR [rdi] ; load radius
- mulsd xmm1, xmm1 ; radius^2
- mulsd xmm1, QWORD PTR [rip+PI] ; * PI
- addsd xmm0, xmm1 ; sum stays in a register
- add rdi, 8 ; next Circle, 8 bytes
- dec rcx
- jnz .loop
The two functions don't see the same data, either. The static one walks a contiguous array of Circles; the dynamic one walks an array of pointers, each of which can land anywhere in memory. Some of the gap you'd measure comes from that layout rather than the vtable, so a fair benchmark gives both versions the same shape (say &[&Circle] against &[&dyn Area]). How big the gap is depends on the workload: when the per-call work is tiny, as here, static dispatch can be several times faster because the compiler can inline, vectorise and unroll once it knows the type. When each call does real work, the indirect call disappears into the noise. Measure your own case rather than trusting a rule of thumb.
When to Use Each
Static dispatch (impl Trait / generics):
- No runtime overhead
- Compiler can inline and optimise
- Generates more code (one copy per type)
- Use when performance matters or types are known at compile time
Dynamic dispatch (dyn Trait):
- Small code size (one function handles all types)
- Enables heterogeneous collections (
Vec<Box<dyn Trait>>) - Runtime overhead from indirection
- Use when you need runtime polymorphism or want to reduce binary size
Object Safety
Not every trait can hide behind a dyn. The trait has to be dyn compatible, which older documentation and error messages call "object safe":
// Dyn compatible - can use as dyntrait Draw { fn draw(&self);}
// NOT dyn compatible - cannot use as dyntrait MyClone { fn my_clone(&self) -> Self; // Returns Self - size unknown at compile time!}
// The real std::Clone is declared like this:// pub trait Clone: Sized { fn clone(&self) -> Self; ... }The reason is mechanical. Calling through a vtable demands a fixed calling convention: argument layout, return-value size, the lot. fn my_clone(&self) -> Self returns something whose size hinges on the concrete type, and dyn MyClone has erased that information. The compiler can't reserve stack space for a return value when it has no idea how big the return value is, so the Reference only lets a dispatchable method use Self as its receiver.
For the standard Clone the rule that bites first is simpler: it declares Sized as a supertrait, and a trait object is unsized by definition, so dyn Clone is ruled out before any method is examined. If you want one method that returns Self on an otherwise dyn-compatible trait, mark that method where Self: Sized; it then can't be called through a dyn, and the rest of the trait can. (Rust Reference, "Traits: Dyn compatibility".)
impl Trait in Return Position
fn make_shape(big: bool) -> impl Area { if big { Circle { radius: 100.0 } } else { Circle { radius: 1.0 } // Must be same type! }}impl Area in return position is still static dispatch. The compiler pins down the concrete type (Circle) and hands it back directly. The caller gets a Circle, not a fat pointer. No indirection, no heap.
That's the trade against Box<dyn Area>, which lets you return different types from each branch but requires heap allocation and pays the dynamic dispatch tax.
Trait Object Memory Layout in Practice
fn examine_sizes() { println!("{}", std::mem::size_of::<&i32>()); // 8 (regular ref) println!("{}", std::mem::size_of::<&dyn Area>()); // 16 (fat pointer) println!("{}", std::mem::size_of::<Box<dyn Area>>()); // 16 (fat pointer) println!("{}", std::mem::size_of::<&[i32]>()); // 16 (fat pointer: ptr + len) println!("{}", std::mem::size_of::<&str>()); // 16 (fat pointer: ptr + len)}Rust ships three flavours of fat pointer:
&dyn Trait= data pointer + vtable pointer&[T]= data pointer + length&str= data pointer + byte length
All 16 bytes. All passed in two registers under the SysV calling convention (rdi + rsi).
You can take a fat pointer apart yourself. The runner transmutes a &dyn Area into its two words, then reads the size and alignment straight out of the vtable. That vtable layout is a rustc implementation detail: fine for poking at, never something to build on. The addresses change from run to run, but the pattern doesn't.
Key Takeaways
-
Static dispatch is monomorphisation. The compiler stamps out a separate, optimised function for each concrete type. Zero overhead at runtime, more bytes in the binary.
-
Dynamic dispatch uses fat pointers. A
&dyn Traitcarries both a data pointer and a vtable pointer — 16 bytes total. -
Rust vtables sit outside the object. Unlike C++, Rust objects don't carry a hidden vtable pointer. You pay only when you reach for
dyn Trait. -
The overhead is two loads plus an indirect call. Mostly invisible. In a hot loop, it's a real cost.
-
You pick the trade. Static vs dynamic dispatch is an explicit choice in the type system, unlike C++ where one
virtualkeyword glues a vtable to the class forever.