So, basically I've wondered how would Kotlin's string interpolation look in Java (decompiled bytecode). At first I've thought it would use StringBuffer (or StringBuilder), or String.format(), but it seems that it does concatenation. Is it really optimal to do so and what about the String Pool?
Here is my Kotlin code:
fun main(args: Array<String>) {
val age : Int = 24
var mySuperString : String = "Dato is ${age} years old!"
println(mySuperString)
}
And here is the Java code which I've decompiled form *.class file:
import java.io.PrintStream;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
@Metadata(mv={1, 1, 6}, bv={1, 0, 1}, k=2, d1={"\000\024\n\000\n\002\020\002\n\000\n\002\020\021\n\002\020\016\n\002\b\002\032\031\020\000\032\0020\0012\f\020\002\032\b\022\004\022\0020\0040\003�\006\002\020\005�\006\006"}, d2={"main", "", "args", "", "", "([Ljava/lang/String;)V", "KotlinProject"})
public final class MainKt
{
public static final void main(@NotNull String[] args)
{
Intrinsics.checkParameterIsNotNull(args, "args");int age = 24;
String mySuperString = "Dato is " + age + " years old!";
System.out.println(mySuperString);
}
}
Even when the string is huge and values are a lot, it still uses the plus signs!
Is this the fastest way or why are they doing this?
The answer is easy: It doesn't
I guess your decompiler is quite sophisticated and also translates the StringBuilder
-append operations to the good old +
concationation.
So if you have a look at the bytecode you see that StringBuilder
is used.
public main(java.lang.String[] arg0) { //([Ljava/lang/String;)V
<localVar:index=3 , name=mySuperString , desc=Ljava/lang/String;, sig=null, start=L1, end=L2>
<localVar:index=2 , name=age , desc=I, sig=null, start=L3, end=L2>
<localVar:index=0 , name=this , desc=Lorg/guenhter/springboot/kt/RandomReceivingController;, sig=null, start=L4, end=L2>
<localVar:index=1 , name=args , desc=[Ljava/lang/String;, sig=null, start=L4, end=L2>
L4 {
aload1
ldc "args" (java.lang.String)
invokestatic kotlin/jvm/internal/Intrinsics checkParameterIsNotNull((Ljava/lang/Object;Ljava/lang/String;)V);
}
L5 {
bipush 24
istore2
}
L3 {
new java/lang/StringBuilder
dup
invokespecial java/lang/StringBuilder <init>(()V);
ldc "Dato is " (java.lang.String)
invokevirtual java/lang/StringBuilder append((Ljava/lang/String;)Ljava/lang/StringBuilder;);
iload2
invokevirtual java/lang/StringBuilder append((I)Ljava/lang/StringBuilder;);
ldc " years old!" (java.lang.String)
invokevirtual java/lang/StringBuilder append((Ljava/lang/String;)Ljava/lang/StringBuilder;);
invokevirtual java/lang/StringBuilder toString(()Ljava/lang/String;);
astore3
}
L1 {
getstatic java/lang/System.out:java.io.PrintStream
aload3
invokevirtual java/io/PrintStream println((Ljava/lang/Object;)V);
}
L6 {
return
}
L2 {
}
}
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