← Back to context

Comment by dmitrygr

3 years ago

Must have been a long time ago. It's been almost a decade since that code pattern started getting compiled into calls to StringBuilder by javac.

It does... but only in one statement.

    String foo = "foo";
    foo += "bar";

That is under the covers...

    String foo = "foo";
    foo = new StringBuilder(foo).append("bar");

But... if you do:

    String foo = "foo";
    foo += "bar";
    foo += "qux";

that becomes

    String foo = "foo";
    foo = new StringBuilder(foo).append("bar");
    foo = new StringBuilder(foo).append("qux");

So, you've still created the strings: "foo", "foobar", and "foobarqux" and also a pair of StringBuilders.

The actual code was more complicated (and bigger strings), but the issue is that each statement is its own StringBuilder.

That prompted me to explore it and I looked at the byte code invocations at http://shagie.net/2014/08/17/what-goes-on-behind-the-scenes-...