Search code examples
javastringjvmstringbuilderjavap

java: String concat in bytecode converted to StringBuilder


I reviewed my compiled code with javac command line and I saw whenever I used String concatenation with + operator, compiled code replaced with StringBuilder's append() method. now I think using StringBuilder and String concatenation have same performance because they have similar bytecode, is it correct?


Solution

  • Yeah, it is true! But when you concatenate in loop the behaviour differs. e.g.

    String str = "Some string";
    for (int i = 0; i < 10; i++) {
      str += i;
    }
    

    new StringBuilder will be constructed at every single loop iteration (with initial value of str) and at the end of every iteration there will be concatenation with initial String (actually StringBuilder with initial value of str).
    So you need to create StringBuilder by yourself only when you work with String concatenation in loop.