Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any performance cost with using "when" instead of "if-else"?

Tags:

kotlin

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?

like image 885
Aba Avatar asked Apr 04 '18 05:04

Aba


1 Answers

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;
}
like image 196
s1m0nw1 Avatar answered Nov 04 '22 21:11

s1m0nw1