Video in progress

Middle ☕ Core Java

How expensive is joining Strings with + in a loop, and what has modern Java changed about it?

In a loop, s += x creates a new String on every iteration and copies the whole text, which makes it O(n²). Since Java 9, a single-expression + runs fast through invokedynamic (StringConcatFactory), but that doesn't fix the loop: there you need StringBuilder.

📖 Answer

String report = "";
for (Order o : orders) {
    report += o.id() + ";" + o.total() + "\n";   // the whole report is copied at every step
}

For 10 thousand lines, that's hundreds of megabytes of temporary objects and GC pressure.

The right way:

StringBuilder sb = new StringBuilder(orders.size() * 32);   // estimated size
for (Order o : orders) {
    sb.append(o.id()).append(';').append(o.total()).append('\n');
}
String report = sb.toString();

Or with a stream:

String report = orders.stream()
        .map(o -> o.id() + ";" + o.total())
        .collect(Collectors.joining("\n"));

Don't worry about a concatenation in a single expression ("Order " + id + " total " + sum): in Java 9+ the JVM assembles it well on its own, and it's often no slower than a hand-written StringBuilder.

String.format is convenient but relatively slow (it parses the format every time). Don't use it in places called very often (for example, on every log line); for logs there are {} placeholders.