Search code examples
javaperformanceintellij-ideastringbuffer

String vs StringBuffer. Tip of IDEA


Intellij Idea offers to replace the following:

StringBuffer sb = new StringBuffer();
sb.append("Name=").append(name).append(", name2=").append(name2).append(", list=").append(list);
return sb.toString();

To:

return "name=" + name + ", name2=" + name2 + ", list=" + list;

As far as I know it's less effective (mutable/immutable). So, what's better?


Solution

  • The second one compiles to the same byte-code as the first one, except it uses a non-synchronized StringBuilder instead of a synchronized StringBuffer. So it's not only much more readable, but also slightly faster. I'd choose the second one.

    Using a StringBuilder is useful when concatenating in a loop, to avoid creating many temporary String objects:

    String result = "";
    for (String element : array) {
        result += element;
    }
    

    should be replaced by

    StringBuilder builder = new StringBuilder();
    for (String element : array) {
        builder.append(element);
    }
    String result = builder.toString();