Quick revision
The short answer
We put the ten strings in a @State(Scope.Thread) class filled in @Setup, so they are not compile-time constants, and write one @Benchmark method per approach that returns the joined string, so dead code elimination cannot remove the work. We configure @Warmup, @Measurement and @Fork, choose average time in nanoseconds, use @Param to vary the string length, and run with -prof gc to compare bytes allocated per operation. We then report the error margins and do not trust differences smaller than them, because the winner can change with input size and JDK version.
What to remember
In this answer, we wrote a JMH benchmark comparing StringBuilder with String.join for ten strings. The inputs live in a @State(Scope.Thread) class filled in @Setup so they are not constants, each @Benchmark method returns its result so it cannot be removed as dead code, and @Warmup, @Measurement and @Fork give stable, repeated measurements in average time per operation. @Param varies string length, -prof gc shows bytes allocated per operation, and we report results with their error margins and context instead of a universal winner.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We put the ten strings in a @State(Scope.Thread) class filled in @Setup, so they are not compile-time constants, and write one @Benchmark method per approach that returns the joined string, so dead code elimination cannot remove the work. We configure @Warmup, @Measurement and @Fork, choose average time in nanoseconds, use @Param to vary the string length, and run with -prof gc to compare bytes allocated per operation. We then report the error margins and do not trust differences smaller than them, because the winner can change with input size and JDK version.
Why this question is asked
Joining strings is everywhere in Java code: building keys, log messages, CSV lines and SQL fragments. Teams often argue about whether a manual StringBuilder is faster than String.join, and the honest answer is that it depends on sizes and JDK version, so we measure. Interviewers ask for this benchmark because writing it correctly shows that we know the classic JMH pitfalls and can produce numbers that mean something. In this answer, we will set up the state, write both benchmark methods, configure the run, add allocation profiling and parameters, and read the results honestly.
1What We Are Comparing
String.join(",", parts) joins an array or iterable of strings with a delimiter. Since JDK 17 its implementation was reworked to first compute the exact length of the result and then copy the characters once, which avoids growing an internal buffer. A StringBuilder, by contrast, starts with a default capacity of 16 characters and doubles its buffer as it grows, copying the contents each time, unless we give it an initial capacity.
So we expect differences in both time and allocation, and they may depend on how long the strings are. That is exactly why the benchmark needs parameters and an allocation profiler, not just a single timing.
2Setting Up the State
The inputs live in a state class. JMH creates state objects, calls their @Setup methods before measurement, and passes them to benchmark methods. Because the fields are ordinary non-final fields filled at runtime, the JIT cannot treat them as constants and fold the work away.
Scope.Thread means each thread running the benchmark gets its own state, which avoids accidental sharing if we later run with several threads. Level.Trial means setup runs once per fork and parameter combination, not inside the measured loop. The fixed seed makes the inputs the same across runs, so differences come from the code, not the data.
3Writing the Benchmark Methods
Each approach gets its own @Benchmark method, and each returns its result. JMH consumes returned values through a Blackhole internally, so the JIT cannot prove the work is unused and delete it.
Notice the third variant, a presized StringBuilder. It is not in the question, but it isolates why the plain StringBuilder might lose: if the difference is buffer growth, presizing should close the gap. Good benchmarks often include such a variant to explain a result rather than just record it.
The annotations configure the run. Five one-second warmup iterations let the JIT compile everything; five measured iterations give repeated samples; three forks run each benchmark in fresh JVMs, because JIT decisions can differ between launches. Average time in nanoseconds per operation is a natural unit for an operation this small.
4Running It and Measuring Allocation
Time alone does not tell the whole story. A version that allocates more creates more work for the garbage collector, which shows up elsewhere in a real service. JMH's GC profiler reports allocation per operation.
The gc.alloc.rate.norm line is bytes allocated per operation, which is stable and very useful: it shows directly that one approach creates intermediate buffers and the other does not. In these illustrative numbers, String.join is clearly faster and allocates less for short strings, while for long strings the two time results overlap within their error margins.
5Reading the Results Honestly
The error column is the confidence interval JMH computes from the measurements. If two scores are 262.0 with an error of 9.4 and 251.3 with an error of 10.2, the intervals overlap, so we cannot say which is faster for long strings; we report them as equal within the measurement's precision. For short strings, 61.2 plus or minus 1.8 against 48.7 plus or minus 1.5 do not overlap, so the difference is real for that case.
We also report the context: JDK version, hardware, the parameters, and the fact that this measures joining in isolation. The winner can change with input size, as @Param shows, and with JDK version, since String.join's implementation changed in JDK 17. So the conclusion is a statement such as String.join is at least as fast as StringBuilder for ten strings on JDK 25 and allocates less for short strings, not a rule that one is always faster. And in most code, readability decides: String.join states the intent in one line.
- Inputs in a @State classfilled in
@Setup, not constants - One @Benchmark per varianteach returns its result
- Warmup, measurement, forks5 x 1 s, 5 x 1 s, 3 forks
- @Param over input sizesthe winner can change
- Run with -prof gcbytes per operation
- Do error intervals overlap?YesReport as equalNoReport the difference with context
6 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Why not use Scope.Benchmark for the state?
Scope.Benchmark shares one state instance among all threads of the benchmark. With a single thread it makes no difference, but if we later run with several threads, shared state can introduce contention or false sharing that has nothing to do with joining. Scope.Thread avoids that for per-thread inputs.
Should we use a Blackhole instead of returning the value?
Returning a single value is enough, because JMH feeds it into a Blackhole for us. We use an explicit Blackhole parameter when a method produces several values, such as results inside a loop, so each one is consumed.
7Conclusion
In this answer, we wrote a JMH benchmark comparing StringBuilder with String.join for ten strings. The inputs live in a @State(Scope.Thread) class filled in @Setup so they are not constants, each @Benchmark method returns its result so it cannot be removed as dead code, and @Warmup, @Measurement and @Fork give stable, repeated measurements in average time per operation. @Param varies string length, -prof gc shows bytes allocated per operation, and we report results with their error margins and context instead of a universal winner.
Open with
I would put the ten strings in a state class annotated with State Scope.Thread and build them in a Setup method at Level.Trial from a seeded Random, so they are runtime values and not compile-time constants the JIT could fold.
Then, if they want more
I would add a Param for string length, say 5 and 50, because the winner can change with size. Then one Benchmark method per approach, the StringBuilder loop, String.join, and I like adding a presized StringBuilder to explain any difference, and each method returns its string so JMH consumes it and dead code elimination cannot remove the work.
I configure BenchmarkMode AverageTime with nanoseconds, five one-second warmup iterations, five measurement iterations and at least three forks, because JIT decisions vary between JVM launches. I run it with -prof gc to get bytes allocated per operation, which shows whether one approach creates intermediate buffers; since JDK 17 String.join computes the exact size first, so it often allocates less.
When reading results I look at the error column: if the intervals overlap, I say they are equal within precision. And I report JDK version, hardware and parameters, because the answer is specific to them.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 17, Java 25
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a JMH benchmark comparing StringBuilder with String.join for joining ten strings...": https://scrivio-interview-library.netlify.app/java/java-performance/8bc2b895a5/