I personaly like the when
syntax as it causes identation to be much clearer. However I am concerned about the 'penalties' that I might be introducing by doing this.
I'm not really an expert on bytecode, but I can see that for the same 'logic', the when clause takes more bytecode operations.
Simple file with 3 different Kotlin functions
package com.whatever
fun method1(): String {
return if (BuildConfig.DEBUG) "something" else "else"
}
fun method2(): String {
return if (BuildConfig.DEBUG) {
"something"
} else {
"else"
}
}
fun method3(): String {
return when (BuildConfig.DEBUG) {
true -> "something"
else -> "else"
}
}
Generated bytecode
// access flags 0x19
public final static method1()Ljava/lang/String;
@Lorg/jetbrains/annotations/NotNull;() // invisible
L0
LINENUMBER 4 L0
GETSTATIC com/whatever/BuildConfig.DEBUG : Z
IFEQ L1
LDC "something"
GOTO L2
L1
LDC "else"
L2
ARETURN
L3
MAXSTACK = 1
MAXLOCALS = 0
// access flags 0x19
public final static method2()Ljava/lang/String;
@Lorg/jetbrains/annotations/NotNull;() // invisible
L0
LINENUMBER 8 L0
GETSTATIC com/whatever/BuildConfig.DEBUG : Z
IFEQ L1
L2
LINENUMBER 9 L2
LDC "something"
L3
GOTO L4
L1
LINENUMBER 11 L1
LDC "else"
L5
LINENUMBER 8 L5
L4
ARETURN
L6
MAXSTACK = 1
MAXLOCALS = 0
// access flags 0x19
public final static method3()Ljava/lang/String;
@Lorg/jetbrains/annotations/NotNull;() // invisible
L0
LINENUMBER 16 L0
GETSTATIC com/whatever/BuildConfig.DEBUG : Z
ISTORE 0
L1
LINENUMBER 17 L1
ILOAD 0
ICONST_1
IF_ICMPNE L2
L3
LDC "something"
GOTO L4
L2
LINENUMBER 18 L2
LDC "else"
L5
LINENUMBER 16 L5
L4
ARETURN
L6
MAXSTACK = 2
MAXLOCALS = 1
Can someone point out how significant this cost is? And wether we should try to stay away from this pattern for simple operations?
Thanks