多次字符串相加一定要用StringBuilder而不用-吗?( 二 )


多次字符串相加一定要用StringBuilder而不用-吗?文章插图
更新与勘误2019-08-13 更新当在循环中对字符串进行 += 操作时 , 会在每一次迭代中都创建一个StringBuilder , 这种在循环内进行字符串 += 操作会被idea提示用 StringBuilder 替代的
package io.since1986.demo;public class Test10 {public static void main(String[] args) {String s = "1111DDDDFFFGGGGG";for (int i = 0; i < 99; i++) {s += "3fghjl";}System.out.println(s);}}// class version 52.0 (52)// access flags 0x21public class io/since1986/demo/Test10 {// compiled from: Test10.java// access flags 0x1public ()VL0LINENUMBER 3 L0ALOAD 0INVOKESPECIAL java/lang/Object. ()VRETURNL1LOCALVARIABLE this Lio/since1986/demo/Test10; L0 L1 0MAXSTACK = 1MAXLOCALS = 1// access flags 0x9public static main([Ljava/lang/String;)VL0LINENUMBER 6 L0LDC "1111DDDDFFFGGGGG"ASTORE 1L1LINENUMBER 7 L1ICONST_0ISTORE 2L2FRAME APPEND [java/lang/String I]ILOAD 2BIPUSH 99IF_ICMPGE L3L4LINENUMBER 8 L4NEW java/lang/StringBuilder// 注意这里是在循环内创建 StringBuilderDUPINVOKESPECIAL java/lang/StringBuilder. ()VALOAD 1INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;LDC "3fghjl"INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;INVOKEVIRTUAL java/lang/StringBuilder.toString ()Ljava/lang/String;ASTORE 1L5LINENUMBER 7 L5IINC 2 1GOTO L2L3LINENUMBER 10 L3FRAME CHOP 1GETSTATIC java/lang/System.out : Ljava/io/PrintStream;ALOAD 1INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)VL6LINENUMBER 11 L6RETURNL7LOCALVARIABLE i I L2 L3 2LOCALVARIABLE args [Ljava/lang/String; L0 L7 0LOCALVARIABLE s Ljava/lang/String; L1 L7 1MAXSTACK = 2MAXLOCALS = 3}2019-08-15 更新GETFIELD test/Test8.s4 : Ljava/lang/String;INVOKEVIRTUAL java/lang/StringBuilder.append (Ljava/lang/String;)Ljava/lang/StringBuilder;LDC "555566666666666666666666666666777"“5555” + “66666666666666666666666666” + “777” 直接被合并在了一块 , 这个操作叫 常量折叠
Java中 , 关于String类型的变量和常量做“+”运算时发生了什么?