StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2191
北恋
北恋 2020-11-21 04:18

Given the 2 toString() implementations below, which one is preferred:

public String toString(){
    return \"{a:\"+ a + \", b:\" + b + \", c: \"         


        
18条回答
  •  孤街浪徒
    2020-11-21 05:07

    Using latest version of Java(1.8) the disassembly(javap -c) shows the optimization introduced by compiler. + as well sb.append() will generate very similar code. However, it will be worthwhile inspecting the behaviour if we are using + in a for loop.

    Adding strings using + in a for loop

    Java:

    public String myCatPlus(String[] vals) {
        String result = "";
        for (String val : vals) {
            result = result + val;
        }
        return result;
    }
    

    ByteCode:(for loop excerpt)

    12: iload         5
    14: iload         4
    16: if_icmpge     51
    19: aload_3
    20: iload         5
    22: aaload
    23: astore        6
    25: new           #3                  // class java/lang/StringBuilder
    28: dup
    29: invokespecial #4                  // Method java/lang/StringBuilder."":()V
    32: aload_2
    33: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    36: aload         6
    38: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    41: invokevirtual #6                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
    44: astore_2
    45: iinc          5, 1
    48: goto          12
    

    Adding strings using stringbuilder.append

    Java:

    public String myCatSb(String[] vals) {
        StringBuilder sb = new StringBuilder();
        for(String val : vals) {
            sb.append(val);
        }
        return sb.toString();
    }
    

    ByteCdoe:(for loop excerpt)

    17: iload         5
    19: iload         4
    21: if_icmpge     43
    24: aload_3
    25: iload         5
    27: aaload
    28: astore        6
    30: aload_2
    31: aload         6
    33: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    36: pop
    37: iinc          5, 1
    40: goto          17
    43: aload_2
    

    There is a bit of glaring difference though. In first case, where + was used, new StringBuilder is created for each for loop iteration and generated result is stored by doing a toString() call(29 through 41). So you are generating intermediate Strings that your really do not need while using + operator in for loop.

提交回复
热议问题