title: Does the order of alternatives in a Scala match expression matter in terms of performance?
body: <p>In particular with respect to pattern matching and case classes. Consider the following:</p>
  
  <pre><code>abstract class Expr
  case class Var(name: String) extends Expr
  case class Number(num: Double) extends Expr
  case class UnOp(operator: String, arg: Expr) extends Expr
  case class BinOp(operator: String, left: Expr, right: Expr) extends Expr
  
  object Expr {
    def simplify(expr: Expr): Expr = expr match {
      // Some basic simplification rules...
      case UnOp("-", UnOp("-", e)) =&gt; simplify(e) // Double negation
      case BinOp("+", e, Number(0)) =&gt; simplify(e) // Adding zero
      case BinOp("-", e, Number(0)) =&gt; simplify(e) // Subtracting zero
      case BinOp("*", e, Number(1)) =&gt; simplify(e) // Multiplying by one
      case BinOp("*", e, Number(0)) =&gt; Number(0) // Multiplying by zero
      case _ =&gt; expr // Default, could not simplify given above rules
    }
  }
  </code></pre>
  
  <p>Given any sample call, say, <code>simplify(UnOp("-", UnOp("-", UnOp("-", UnOp("-", Var("x"))))))</code> (which results in <code>Var("x")</code>), does the order of the alternatives in the match expression matter for performance?</p>
  
  <p><strong>Side note, kind of related (my own observation):</strong> One thing that really strikes me about <code>simplify</code> is that it is a recursive function, although unlike other recursive functions I've written / dealt with, the base case comes last in order to avoid terminating early.</p>