Michael Ekstrand
Michael Ekstrand

Reputation: 29090

How much optimization does Scala's pattern matcher perform?

Suppose I have a Scala match expression

foo match {
    case Bar(Some(x)) => /* do something */
    case Bar(None)    => /* do something else */
}

How much optimization does the compiler do when it compiles the expression? In particular, does it emit multiple calls to Bar.unapply, or does it make a single call and match multiple times on the result?

Upvotes: 5

Views: 154

Answers (1)

dhg
dhg

Reputation: 52691

You can check this yourself with a little code:

object Bar {
  def unapply(x: Int): Option[Option[Int]] = {
    println("Checking: " + x)
    Some(None)
  }
}

1 match {
  case Bar(Some(x)) => println("do something")
  case Bar(None)    => println("do something else")
}

When you run it, you get:

Checking: 1
do something else

So it looks like Scala is not doing multiple calls to Bar.unapply even though the code looks like there would be multiple calls. This is good from the standpoint of efficiency, but you should probably avoid side-effects in your unapply methods that rely on them getting called multiple times per match-statement.

If you were worried about when the optimization happens and making it clear to the reader that the unapply is only being called once, you could split up the matches quite easily:

1 match {
  case Bar(y) => y match {
    case Some(x) => println("do something")
    case None    => println("do something else")
  }
}

Upvotes: 7

Related Questions