Search code examples
rusttraitsdynamic-dispatchstatic-dispatch

Do Rust traits have runtime overhead?


Is there any runtime overhead if I create c1 of type Concrete1 in the code below?

pub trait ExampleTrait {
    fn foo(&self);
}

pub struct Concrete1 {}

impl ExampleTrait for Concrete1 {
    fn foo(&self) {}
}

pub struct Concrete2 {}

impl ExampleTrait for Concrete2 {
    fn foo(&self) {}
}

fn main() {
    let c1 = Concrete1 {};
    c1.foo();
}

Does this entail any sort of v-table lookup or any other kind of overhead? I want a trait so that I can enforce at compile time that both Concrete1 and Concrete2 implement the same set of methods.

I will statically choose which concrete type to use in the main program; the two implementations exist just so that I can use an alternative implementation of the trait if need arises.


Solution

  • If the concrete type is known statically, then static dispatch is used.

    If the concrete type is not known (i.e. a trait object: &dyn ExampleTrait), then dynamic dispatch is used.

    See also: