Part 13 / Topic 6 of 8
Measuring performance honestly
Before trusting any "X is faster than Y," a benchmark has to be fair: warm up first (run both candidates enough times that the JIT has already compiled them — section 5), then time many repeats and compare totals, never a single run, which is noisy.
static String concatLoop(int n) {
String result = "";
for (int i = 0; i < n; i++) {
result += "line " + i + ";"; // each += allocates a brand-new String (section 3)
}
return result;
}
static String builderLoop(int n) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++) {
result.append("line ").append(i).append(";"); // grows one mutable buffer in place
}
return result.toString();
}
$ javac StringConcatVsBuilder.java
$ java StringConcatVsBuilder
== Warm-up: 200 repeats of each, building a 2000-line string, result discarded ==
== Timed: 200 repeats of each, after warm-up ==
string += in a loop: 124 ms total (200 repeats, 2000 lines each)
StringBuilder.append: 5 ms total
StringBuilder was about 22.8x faster here
(varies by machine and run — the ratio is what matters, not the millisecond counts)
Both built the identical text; only the number of intermediate objects differs:
concatLoop(5) == builderLoop(5): true
Each += in concatLoop allocates a brand-new String holding the old content plus the new piece — building a 2,000-line string this way creates (and immediately discards) roughly 2,000 intermediate strings, each one longer than the last. StringBuilder grows one mutable backing array in place, only copying it on the rare occasion it needs to grow bigger, and it was roughly 23 times faster here for exactly that reason. Both produce byte-for-byte identical output — the difference is purely about how many objects it took to get there, not about correctness.
| Tool | Use it for |
|---|---|
System.nanoTime() difference |
timing one block of code, with your own warm-up and repeat loop |
-Xlog:gc |
seeing actual garbage-collection pauses (section 2) |
javap -c |
reading the bytecode a method compiled to (section 5) |
-Xint vs. default |
isolating how much the JIT itself is buying you (section 5) |
⚠️ A single timed run proves almost nothing. The JVM hasn't warmed up yet, and background noise (another process, a GC pause at the wrong moment) can swing one run by a large factor. Warm up, then time many repeats, then compare totals.
Full program: examples/StringConcatVsBuilder.java.
Done here? The practice set for Part 13 — including the solutions — is on the part page.