Best practices/performance: mixing StringBuilder.append with String.concat

前端 未结 9 510
孤独总比滥情好
孤独总比滥情好 2020-12-07 08:23

I\'m trying to understand what the best practice is and why for concatenating string literals and variables for different cases. For instance, if I have code like this

相关标签:
9条回答
  • 2020-12-07 08:59

    The compilier optimize the + concatenation.

    So

    int a = 1;
    String s = "Hello " + a;
    

    is transformed into

    new StringBuilder().append("Hello ").append(1).toString();

    There an excellent topic here explaining why you should use the + operator.

    0 讨论(0)
  • 2020-12-07 09:06

    I personally prefer the Strings.format(), simple easy to read one-line string formatter.

    String b = "B value";
    String d = "D value";
    String fullString = String.format("A %s C %s E F", b, d);
    // Output: A B value C D value E F
    
    0 讨论(0)
  • 2020-12-07 09:14

    You should always use append.

    concat create a new String so it's pretty like + I think.

    If you concat or use + with 2 final String the JVM can make optimisation so it's the same as doing append in this case.

    0 讨论(0)
提交回复
热议问题