Which Java String Concatenation Method Is Fastest? JMH Benchmarks Reveal Surprising Results
This article examines eight common Java string concatenation techniques, benchmarks them with JMH, presents the performance results—including a clear ranking where the '+' operator outperforms others—and provides a downloadable Spring Boot 3 case collection for deeper learning.
The article introduces a Spring Boot 3 practical case collection and focuses on the performance comparison of eight string concatenation methods in Java.
1. Introduction
String concatenation is a frequent operation in development, used in logging, data processing, UI generation, and more. Different concatenation approaches have significant performance differences that developers often overlook.
2. Eight Concatenation Methods
"+" operator
String#concat
String#join
String#format
Stream API
StringBuffer
StringBuilder
StringJoiner
3. JMH Benchmark Setup
The benchmarks are written using JMH. Each method is measured with the following annotations:
// Warmup 1s, 3 iterations
@Warmup(iterations = 3, time = 1)
// Fork 1 JVM with 512m heap
@Fork(value = 1, jvmArgsAppend = {"-Xms512m", "-Xmx512m"})
// Measure average time
@BenchmarkMode(Mode.AverageTime)
// Output in nanoseconds
@OutputTimeUnit(TimeUnit.NANOSECONDS)
// 10 measurement iterations, 2s each
@Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS)
public class StringJoinTest {
// The eight concatenation methods are placed here
}The benchmark can be run via a main method:
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(StringJoinTest.class.getSimpleName())
.forks(1)
.build();
new Runner(options).run();
}4. Benchmark Results
The following chart shows the measured average time (ns/op) for each method:
Key observations:
The "+" operator is the most efficient.
String#format is the slowest by a large margin.
5. Performance Ranking
plusOperator : 6.154 ± 0.119 ns/op
concat : 8.584 ± 0.175 ns/op
stringBuilder : 11.560 ± 0.216 ns/op
stringBuffer : 12.340 ± 0.150 ns/op
stringJoiner : 29.932 ± 0.236 ns/op
join : 28.210 ± 0.241 ns/op
stream : 34.293 ± 0.284 ns/op
format : 409.691 ± 2.941 ns/op
These results demonstrate that simple concatenation with the "+" operator outperforms more complex APIs in single‑threaded scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
