Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of PartialFunction orElse

Tags:

scala

Is the use of a PartialFunction's orElse more or less efficient than using a large match block during apply time?

To illustrate the question, is:

val pf = { case "a" => "A"} orElse 
         { case "b" => "B" } orElse 
         { case "c" => "C" } ...

more or less efficient than:

val pf = { case "a" => "A"
  case "b" => "B"
  case "c" => "C"
  ...
}

during application a value to pf:

pf(x)
like image 707
Chris Stivers Avatar asked Feb 28 '12 06:02

Chris Stivers


2 Answers

See this detailed analysis from the author of unfiltered. It's basically less efficient. I believe some work has been done in trunk to address this, shortly after the blog post was made.

like image 144
huynhjl Avatar answered Oct 03 '22 23:10

huynhjl


The second case cannot possibly be less efficient than the first, because the compiler could just convert it into the first (and, in fact, that's not far from what the virtual pattern matcher does).

So, if you have the choice, the second case is always the safer bet.

like image 35
Daniel C. Sobral Avatar answered Oct 04 '22 00:10

Daniel C. Sobral