-
-
Notifications
You must be signed in to change notification settings - Fork 624
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use if-else vs pattern matching for booleans #24
Comments
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 |
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
The text was updated successfully, but these errors were encountered: