String a = "abc";
String b = "xyz";
String result = a + b;
我想知道“result”字符串是字符串池中的String常量分配内存还是堆上创建的新对象。
我知道新的String()在堆上创建对象,并且在permgen字符串池空间中的上例中的字符串常量如a,b。
答案 0 :(得分:8)
重要提示:
String a = "abc";
String b = "xyz";
String result = a + b;
与
相同// creates a number of objects.
String result = new StringBuilder().append(a).append(b).toString();
但
final String a = "abc";
final String b = "xyz";
String result = a + b;
与
相同String result = "abcxyz"; // creates no new objects.
答案 1 :(得分:2)
如果您编译并反编译代码,它将给出以下结果:
String result = new StringBuilder().append(a).append(b).toString();
答案 2 :(得分:0)
连接导致分配StringBuilder以创建连接字符串。
来源:
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;
}
}
通过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
}
您可以在第10行看到StringBuilder
分配,用于连接字符串a
和b
。请注意,编译器在第25行处理CONST1和CONST2的串联。因此,如果您的字符串为final
,则不会导致StringBuilder
分配