scala-best-practices icon indicating copy to clipboard operation
scala-best-practices copied to clipboard

Use if-else vs pattern matching for booleans

Open smajithia76 opened this issue 10 years ago • 8 comments

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

smajithia76 avatar Aug 05 '15 08:08 smajithia76

Thanks, will mention it.

alexandru avatar Aug 13 '15 10:08 alexandru

anything around this in Effective Scala?

umeshksingla avatar Sep 06 '18 18:09 umeshksingla

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?

mauriciojost avatar Sep 06 '18 20:09 mauriciojost

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.

wookietreiber avatar Sep 07 '18 08:09 wookietreiber

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

franklinchou avatar Aug 07 '19 15:08 franklinchou

Any consensus?

jfernandrezj avatar May 24 '23 09:05 jfernandrezj

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

mdedetrich avatar Jan 20 '24 20:01 mdedetrich

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.

som-snytt avatar Jan 22 '24 22:01 som-snytt