从指令看出new String(“hello1”),这个创建了2个对象
public void anew(){
String str = new String("hello1");
}
指令
0 new #14 <java/lang/String> // 第2个对象
3 dup
4 ldc #15 <hello1> // 第1个对象
6 invokespecial #16 <java/lang/String.<init>>
9 astore_1
10 return
例子2
public void notnew(){
String str = "hello2";
}
指令
0 ldc #17 <hello2>
2 astore_1
3 return
例子3
public void notnew2(){
String str = new StringBuilder("Hello").append("World").toString();
}
指令
0 new #2 <java/lang/StringBuilder>
3 dup
4 ldc #3 <Hello>
6 invokespecial #4 <java/lang/StringBuilder.<init>>
9 ldc #5 <World>
11 invokevirtual #6 <java/lang/StringBuilder.append>
14 invokevirtual #7 <java/lang/StringBuilder.toString>
17 astore_1
18 return
例子4
public void notnew3(){
String str = "a"+"b";
}
指令
从指令,可以看出"a"+“b”,已经被优化了
0 ldc #18 <ab>
2 astore_1
3 return
例子5
public void notnew4(){
String a = "a";
String b = "b";
String str = a+b;
}
指令
从指令可以看出a+b,使用的是StringBuilder对象操作
0 ldc #19 <a>
2 astore_1
3 ldc #20 <b>
5 astore_2
6 new #2 <java/lang/StringBuilder>
9 dup
10 invokespecial #10 <java/lang/StringBuilder.<init>>
13 aload_1
14 invokevirtual #6 <java/lang/StringBuilder.append>
17 aload_2
18 invokevirtual #6 <java/lang/StringBuilder.append>
21 invokevirtual #7 <java/lang/StringBuilder.toString>
24 astore_3
25 return