4

Let's say you have an enum

enum Expr {
 binExp, unExp, Literal, Group 
}

And you want to call methods on Expr.

Would you rather :

match Expr { 
 Expr::binExp  => todo!(),
 Expr::unExp   => todo!(),
 Expr::Literal => todo!(),
 Expr::Group   => todo!()
}

OR

if let Expression::binExp = self {
  todo!()
} else if let Expression::unExp = self {
  todo!()
} else if let Expression::Lit = self {
  todo!()
} else if let Expression::Group(e) = self {
  todo!()
} else {
  todo!()
}

Stated another way, is match a parallel operation? I know if/else will go through each expression sequentially, evaluating them as they are encountered as false and finally make a stop.

Do match statements mimic this behavior or do they directly jump to the correct pattern? I ask this specifically because match can match on multiple patterns, but always select the pattern that matches it first. So it does sound like match may be sequential in that regard.

3
  • 6
    When built in release mode, both match and if let chains deploy powerful optimizations to generate the fastest possible code. Nothing is guaranteed, but for the simple cases outlined in the question, I would expect the same (optimal) code to be generated by both. Apr 9, 2022 at 10:01
  • 2
    Generally yes, but the compiler is made out of eldritch black magic so it will probably figure out how to optimize it to the same result either way. The best option is whichever you feel makes your code most verbose and maintainable.
    – Locke
    Apr 9, 2022 at 10:02
  • 3
    @Locke: least verbose and most maintainable surely?
    – hkBst
    Apr 9, 2022 at 10:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.