所以,基本上我想知道Kotlin的字符串插值在Java中是如何看的(反编译的字节码)。起初我以为它会使用StringBuffer(或StringBuilder)或String.format(),但似乎它确实连接。这样做真的是最佳的吗?字符串池呢?
这是我的Kotlin代码:
fun main(args: Array<String>) {
val age : Int = 24
var mySuperString : String = "Dato is ${age} years old!"
println(mySuperString)
}
这是我用* .class文件反编译的Java代码:
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);
}
}
即使字符串很大且值很多,它仍然使用加号!
这是最快的方式还是他们为什么要这样做?
答案 0 :(得分:11)
答案很简单:它没有
我想你的反编译器非常复杂,并且还会将StringBuilder
- 追加操作转换为良好的旧+
分词。
因此,如果您查看字节码,您会看到StringBuilder
被使用。
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 {
}
}