https://kotlinlang.org logo
Title
k

Kroppeb

02/10/2020, 2:05 PM
fun addStatement(statement: Statement?){
	statement?.let{
		statements.add(it)
	}
}
or less indentation
fun addStatement(statement: Statement?){
	statement?:return
	statements.add(statement)
}
or just old reliable
fun addStatement(statement: Statement?){
	if(statement != null)
		statements.add(statement)
}
3️⃣ 7
2️⃣ 2
1️⃣ 4
What if instead of
statements.add(...)
it would be a longer piece of code? Would 2 be more desired to reduce indentation?
a

arekolek

02/10/2020, 2:22 PM
4️⃣
fun addStatement(statement: Statement?) {
    statement?.let(statements::add)
}
3
5️⃣
fun addStatement(statement: Statement?) {
    if (statement == null) return
    statements.add(statement)
    // a lot of other stuff with statement
}
if it was longer
1
k

Kristoffer Andersen

02/10/2020, 2:53 PM
3 and 5 generate absolutely the smallest, equivalent bytecode, followed by 2. 1 and 4 are showing artifacts of the inliner and the implementation of function references, but it would be interesting to know how they JIT - I would suspect all 5 compile to the same native code, depending on platform.
k

Kroppeb

02/10/2020, 2:59 PM
2:
L0
    LINENUMBER 11 L0
    ALOAD 0
    DUP
    IFNULL L1
    GOTO L2
   L1
    LINENUMBER 11 L1
    POP
    RETURN
   L2
    POP
5:
L0
    LINENUMBER 24 L0
    ALOAD 0
    IFNONNULL L1
    RETURN
It's weird that the compiler does 2 in such a convoluted way.
k

Kristoffer Andersen

02/10/2020, 3:00 PM
Yeah, the stack and local gymnastics most of these display are byproducts of the compilation.
k

Kroppeb

02/10/2020, 3:02 PM
It's caused by the
DUP
and
POP
. I find it weird they are placed there in the first place and the first non-control flow op executed afterwards is always a
POP
I guess just trust upon the jit to fix it
d

Daniel

02/11/2020, 6:27 PM
None of the above. The signature should be
fun addStatement(statement: Statement){
	// ...
}
And don't call the method if you don't have a statement. Thats the nice thing in kotlin, you can control your api in relation to null! 🙂