0

Assume we have nullable val a: Boolean?.

In code we want to assign value of a to another non-nullable variable val b: Boolean.

If a is true then we want b also to be true

If a is false or null the we want b to be false.

We can do this in 2 ways:

b = a ?: false

or

b = a == true

Which of the following approaches is better in terms of performance?

Dmitriy Fialkovskiy
  • 3,065
  • 8
  • 32
  • 47
  • 2
    `a ?: false` contains a conditional jump, but `a == true` does not. The actual answer probably depends on how often is `a` null, so please [race your horses](https://ericlippert.com/2012/12/17/performance-rant/). – Sweeper Dec 22 '22 at 09:53
  • For any code executed often enough to make performance non-trivial, the JVM will probably optimise it enough to make both ways effectively identical. But even if not, I'd be massively surprised if the difference was significant in any real-life application. The effects of memory allocation, (non-inlined) function calls, accessing remote resources, and especially algorithm differences are likely to make many orders of magnitude more difference. Remember [Jackson's rules of optimisation](https://softwareengineering.stackexchange.com/a/99463/314543)… – gidds Dec 22 '22 at 21:13

0 Answers0