Skip to content
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

Open
smajithia76 opened this issue Aug 5, 2015 · 8 comments
Open

Use if-else vs pattern matching for booleans #24

smajithia76 opened this issue Aug 5, 2015 · 8 comments

Comments

@smajithia76
Copy link

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

@alexandru
Copy link
Owner

Thanks, will mention it.

@umeshksingla
Copy link

anything around this in Effective Scala?

@mauriciojost
Copy link

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?

@wookietreiber
Copy link
Contributor

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.

@franklinchou
Copy link

Any consensus on this? Or are we letting this go as a matter of style?

@jfernandrezj
Copy link

Any consensus?

@mdedetrich
Copy link

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

@som-snytt
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants