← All benchmarksJava

Java StringBuilder vs += in a loop: 0.5 ms vs 448 ms

Is StringBuilder faster than string concatenation in a loop in Java?

Yes. Appending one character 100,000 times took 448 ms with s += "x" and 0.5 ms with StringBuilder.append on JDK 17 after JIT warm-up, about 900 times faster, because strings are immutable and every += copies the whole string.

Results

s += "x" (100,000 appends)448 ms
StringBuilder.append (100,000 appends)0.5 ms

How it was measured

100,000 single-character appends, three rounds in one JVM, third round reported. Quick test, not JMH.

String s = "";
for (int i = 0; i < 100_000; i++) s += "x";

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100_000; i++) sb.append("x");

Why

Java strings are immutable. Each += allocates a new string and copies the old content, so total work grows with the square of the length. StringBuilder appends into one growing buffer.

When this does not apply

A few concatenations outside a loop are fine, and the compiler optimizes simple expressions. Use JMH for rigorous comparisons.

Environment

MacBook Air (Apple silicon, 8 cores), macOS, JDK 17. Measured 2026-10-12.

Source: shorts/demo-ticket/java/Concat.java in my content-engine repository. Treat any single run as a direction; re-run it on your hardware.

FAQ

Does the Java compiler optimize string concatenation?
It optimizes a single expression such as a + b + c, but not repeated += inside a loop.

Related

By Josué Barros, senior software engineer (full-stack, data and AI).