What Is the Cost of Dynamic Dispatch (dyn Trait) in Rust?
The cost of dynamic dispatch using dyn Trait is a single pointer indirection per method call, which prevents the compiler from inlining the function. Unlike static dispatch, the compiler cannot determine the concrete type at compile time, so it must look up the method in a virtual table (vtable) at runtime. This adds a small performance overhead compared to monomorphized code but allows storing heterogeneous types in collections.
trait MyTrait {
fn do_something(&self);
}
fn process(item: &dyn MyTrait) {
item.do_something(); // Indirect call via vtable
}
struct Foo;
impl MyTrait for Foo {
fn do_something(&self) {
println!("Foo is doing something");
}
}
fn main() {
let foo = Foo;
process(&foo);
}