alexandru / scala-best-practices

A collection of Scala best practices
4.39k stars 623 forks source link

Use if-else vs pattern matching for booleans #24

Open smajithia76 opened 9 years ago

smajithia76 commented 9 years ago

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 commented 9 years ago

Thanks, will mention it.

umeshksingla commented 6 years ago

anything around this in Effective Scala?

mauriciojost commented 6 years ago

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 commented 6 years ago

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 commented 5 years ago

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

jfernandrezj commented 1 year ago

Any consensus?

mdedetrich commented 9 months ago

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 commented 9 months ago

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.