0

On a philosophical level, traits tend to be a better solution than enums for continuously extending types (at least that's what I've heard). They also provide a nice polymorphism substitute for inheritance. But, on a performance level, are traits more expensive than enums?

fn main() {
    let x = get_x();

    x.foo();
}

Trait Solution:

trait Foo {
    fn foo(&self);
}

struct A;
impl Foo for A {
    fn foo(&self) {
        println!("Doing A stuff...");
    }
}

struct B;
impl Foo for B {
    fn foo(&self) {
        println!("Doing B stuff...");
    }
}

fn get_x() -> impl Foo { A }

Enum Solution:

enum Foo {
    A,
    B,
}

impl Foo {
    fn foo(&self) {
        match self {
            Self::A => println!("Doing A stuff..."),
            Self::B => println!("Doing B stuff..."),
            _ => println!("Not implemented yet"),
        }
    }
}

fn get_x() -> Foo { Foo::A }

With the trait solution I only have to implement its functions for a new type, but with the enum solution I have to add a variant, change the implementation itself, while always needing a "_" case to prevent breaking changes. Am I sacrificing any speed by preferring a trait design over an enum design?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
springworks00
  • 104
  • 15
  • What do your benchmarks say the difference in speed is? – Shepmaster Mar 24 '20 at 19:12
  • 2
    In that case, you aren’t. In cases with `dyn`, you could be. But generally enums are for times when you need to know the full set of options at some point, so just pick the right tool for the job. – Ry- Mar 24 '20 at 19:12
  • 1
    Adding on to the point about `dyn`: [What does “dyn” mean in a type?](https://stackoverflow.com/q/50650070/155423) – Shepmaster Mar 24 '20 at 19:16
  • 2
    It looks like your question might be answered by the answers of [What are the actual runtime performance costs of dynamic dispatch?](https://stackoverflow.com/q/28621980/155423); [How can I avoid dynamic dispatch?](https://stackoverflow.com/q/49227286/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Mar 24 '20 at 19:16
  • 1
    @Shepmaster Yes, those links are more than adequate. I think I was unaware of the proper vocabulary. – springworks00 Mar 24 '20 at 19:21

0 Answers0