String a = "abc";
String b = "xyz";
String result = a + b;
I was wondering if "result" string is a String constant allocated memory in string pool or a new object created on heap.
I know that new String() creates object on heap and String constants like a,b in the above example in permgen string pool space.
An important note:
String a = "abc";
String b = "xyz";
String result = a + b;
is the same as
// creates a number of objects.
String result = new StringBuilder().append(a).append(b).toString();
but
final String a = "abc";
final String b = "xyz";
String result = a + b;
is the same as
String result = "abcxyz"; // creates no new objects.
如果你编译和反编译你的代码,它会给出以下结果:
String result = new StringBuilder().append(a).append(b).toString();
The concatenation results in the allocation of a StringBuilder to create the concatenated string.
Source:
public class Hello {
public static final String CONST1 = "cafe";
public static final String CONST2 = "babe";
public static void main(String[] args){
String a = "abc";
String b = "xyz";
String result = a + b;
String result2 = CONST1 + CONST2;
}
}
Disassembled via javap:
public class Hello extends java.lang.Object{
public static final java.lang.String CONST1;
public static final java.lang.String CONST2;
public Hello();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2; //String abc
2: astore_1
3: ldc #3; //String xyz
5: astore_2
6: new #4; //class java/lang/StringBuilder
9: dup
10: invokespecial #5; //Method java/lang/StringBuilder."<init>":()V
13: aload_1
14: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
17: aload_2
18: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
24: astore_3
25: ldc #8; //String cafebabe
27: astore 4
29: return
}
You can see the StringBuilder
allocation at line 10 for concatenating String a
and b
. Notice the concatenation of CONST1 and CONST2 is processed by the compiler at line 25. So if your Strings are final
it will not result in a StringBuilder
allocation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.