While developing, I've found that using when
looks nicer a lot of the times compared to if-else
. So, I'm curious whether using when
instead of the typical if-else
in simple situations have a performance impact (even if it's small). An example is doing:
val someNumber = when (someObject) {
null -> 0
else -> someCalculation()
}
versus
val someNumber = if (someObject == null) {
0
} else {
someCalculation()
}
Is there a performance difference between the two?
tl;dr: No you should not expect when
to slow anything down.
The compiler reuses if/else, switch and ternary operator constructs in order to express when
statements. Take this example:
fun whenApplication(someObject: String?) = when (someObject) {
null -> 0
else -> 2
}
And its bytecode shown as Java code:
public static final int whenApplication(@Nullable String someObject) {
return someObject == null ? 0 : 2;
}
Slightly more complex when-tests are shown here:
fun whenApplication(someObject: Any?) = when (someObject) {
is Int -> 2
in 0..2 -> 4
else -> 5
}
And the corresponding bytecode as Java:
public static final int whenApplication(@Nullable Object someObject) {
int var10000;
if (someObject instanceof Integer) {
var10000 = 2;
} else {
byte var2 = 0;
var10000 = CollectionsKt.contains((Iterable)(new IntRange(var2, 2)), someObject) ? 4 : 5;
}
return var10000;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With