Open smajithia76 opened 9 years ago
Thanks, will mention it.
anything around this in Effective Scala?
More efficient? It does not seem to be true. In my team we had many times this discussion, so I ended up benchmarking: https://mauriciojost.github.io/scala-benchmark/ and the result is slightly better performance for pattern matching. Plus, isn't it better to stick to declarative statements rather than procedural ones?
In general, you should always prefer clean code over micro-optimizations and this project should do, too.
Also, this is something the compiler should be able to convert / optimize if it sees matching on a Boolean value. If you recognize bytecode for pattern matching on a Boolean that is not converted to an if then else (or whatever is most efficient), it is worth opening an issue for that with the Scala compiler devs. It's better to tackle the problem at its source than to guide people into technical debt.
I vote to close this as wontfix.
Any consensus on this? Or are we letting this go as a matter of style?
Any consensus?
All I can say is that historically in Akka and with the open source variant of Pekko, we use this pattern all of the time as a micro optimization.
Its unclean/annoying so its only worth it for hot path code but yes if you are trying to make the fastest code possible in the hot path you need to use this trick.
It is annoying that the Scala compiler/s is not able to generate this optimized version
I edited the SO example by Ichoran to show -opt:local
on 2.13.12 is identical bytecode. With case _
instead of case false
, you avoid extra MatchError
throwing.
The general guideline for Scala developers is to prefer pattern matching over if-else which is true. However the compiler generates lot of code under the hood if pattern matching used for booleans. For booleans, plain old if-else is still more efficient.
Reference: http://stackoverflow.com/questions/9266822/pattern-matching-vs-if-else