Make a file like this
PlainString.java
import java.time.LocalDateTime;
class PlainString {
String getString() {
//e! String+I will connect with! ??
return "abc" + LocalDateTime.now();
}
}
Compile
javac PlainString.java
I tried decompiling.
javap -c PlainString
Compiled from "PlainString.java"
class PlainString {
PlainString();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
java.lang.String getString();
Code:
0: new #2 // class java/lang/StringBuilder
3: dup
4: invokespecial #3 // Method java/lang/StringBuilder."<init>":()V
7: ldc #4 // String abc
9: invokevirtual #5 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
12: invokestatic #6 // Method java/time/LocalDateTime.now:()Ljava/time/LocalDateTime;
15: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/Object;)Ljava/lang/StringBuilder;
18: invokevirtual #8 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
21: areturn
}
It was firmly replaced by StringBuilder
.
~~ Imadoki's Java seems to be okay to concatenate strings using + without worrying about it. ~~
** Added on 2020/2/22 ** We received a comment from @ cfm-art. Thank you very much.
If you just want to concatenate, + is fine.
If you use + in a loop, StringBuilder
will be created each time, so it's useless.
I was told that StringBuilder is not used after JDK11, so I tried it.
I did javac and then javap.
javap -c PlainString Compiled from "PlainString.java"
class PlainString {
PlainString();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
java.lang.String getString();
Code:
0: invokestatic #7 // Method java/time/LocalDateTime.now:()Ljava/time/LocalDateTime;
3: invokedynamic #13, 0 // InvokeDynamic #0:makeConcatWithConstants:(Ljava/time/LocalDateTime;)Ljava/lang/String;
8: areturn
}
The StringBuilder
disappeared and was replaced by something called makeConcatWithConstants
.
It seems okay to use + anywhere for string concatenation.
openjdk version "13.0.2" 2020-01-14 OpenJDK Runtime Environment AdoptOpenJDK (build 13.0.2+8) OpenJDK 64-Bit Server VM AdoptOpenJDK (build 13.0.2+8, mixed mode, sharing)
Recommended Posts