String 中“+” 的操作的补充说明
在使用“+”的时候,会创建一个StringBuilder对象,然后invokevirtual append()操作
“+”操作创建StringBuilder的粒度是行代码。
String str = a+b+c;
这就是一行,这样他就会只new 一个StringBuider对象然后执行append操作,最后在调用toString()操作。
下面是两个例子:
public class Main{ public static void main(String[]args){ String a ="a",b="b",c="c"; String d = a+b+c; } }
这段简单代码的源码
public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=5, args_size=1 0: ldc #2 // String a 2: astore_1 3: ldc #3 // String b 5: astore_2 6: ldc #4 // String c 8: astore_3 9: new #5 // class java/lang/StringBuilder 12: dup 13: invokespecial #6 // Method java/lang/StringBuilder."<init>":()V 16: aload_1 17: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 20: aload_2 21: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 24: aload_3 25: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 28: invokevirtual #8 // Method java/lang/StringBuilder.toString:()Ljava/lang/String; 31: astore 4 33: return LineNumberTable: line 3: 0 line 4: 9 line 5: 33
在上面字节码文件中可以看见只有一个new(第九行),然后就执行了相关append 操作。-----------行粒度,这里是一行。、
下面设置为两行:
1 public class Main{ 2 public static void main(String[]args){ 3 String a ="a",b="b",c="c"; 4 String d = a+b; 5 d = d+c; //切为两行 6 } 7 }
在次看看字节码
public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=5, args_size=1 0: ldc #2 // String a 2: astore_1 3: ldc #3 // String b 5: astore_2 6: ldc #4 // String c 8: astore_3 9: new #5 // class java/lang/StringBuilder 12: dup 13: invokespecial #6 // Method java/lang/StringBuilder."<init>":()V 16: aload_1 17: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 20: aload_2 21: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 24: invokevirtual #8 // Method java/lang/StringBuilder.toString:()Ljava/lang/String; 27: astore 4 29: new #5 // class java/lang/StringBuilder 32: dup 33: invokespecial #6 // Method java/lang/StringBuilder."<init>":()V 36: aload 4 38: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 41: aload_3 42: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 45: invokevirtual #8 // Method java/lang/StringBuilder.toString:()Ljava/lang/String; 48: astore 4 50: return LineNumberTable: line 3: 0 line 4: 9 line 5: 29 line 6: 50
在 9 、29两行 new