1

Is there any difference in the performance of a partial function defined as

val matches = {
   case Match(x,y) => ...
   case AnotherMatch(x,y,z) => ...
   case x:YetAnother => ...
}

and one defined as below?

val match1 = {
   case Match(x,y) => ... 
}
val match2 = {
   case AnotherMatch(x,y,z) => ...
}
val match3 = {
   case x:YetAnother => ...
}
val matches = match1 orElse match2 orElse match3
Cristian Vrabie
  • 3,972
  • 5
  • 30
  • 49
  • 7
    Yes. Most of the time it's likely to be negligible, though, and if the latter approach in any way makes your code more readable or maintainable, you should use it, and only optimize when you've confirmed that the performance is a real issue in your application. – Travis Brown Jan 07 '15 at 18:13

1 Answers1

1

The difference is about a factor of 2 if the matches are

Some(x: Int) if x > 0 => x
Some(x: Int) if x < 0 => -x
None => 0

So it can be significant in a tight loop, but often won't be.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407