Why ‘+’ Can Beat StringBuilder in Java: Benchmarks and Best Practices
This article investigates the performance differences between Java’s ‘+’ operator and StringBuilder for both simple and looped string concatenations, presenting JUnit benchmark results that show ‘+’ is comparable for single concatenations but significantly slower in loops, and recommends using the appropriate method based on context.
Normal Concatenation
Many developers believe that using
StringBuilderis always faster than the
+operator for concatenating strings. Since JDK 5, the Java compiler automatically rewrites
+concatenations into
StringBuildercalls, so the two approaches generate identical bytecode.
Benchmark: Simple Concatenation
A test class
StringTestcontains two methods—one using
+and one using
StringBuilder—each called 100,000 times in a JUnit test. The results are:
<code>testStringConcatenation01ByPlus,拼接字符串100000次,花费33秒
testStringConcatenation02ByStringBuilder,拼接字符串100000次,花费36秒
</code>The difference is minimal; both methods take roughly the same time, confirming that for single concatenations the
+operator is as efficient as
StringBuilder.
Loop Concatenation
When concatenating inside a loop, using
+repeatedly creates a new
StringBuilderinstance each iteration, leading to much higher overhead. A benchmark comparing looped
+versus a single
StringBuilderinstance shows a dramatic performance gap.
<code>testLoopStringConcatenation03ByPlus,拼接字符串10000次,花费463秒
testLoopStringConcatenation04ByStringBuilder,拼接字符串10000次,花费13秒
</code>The
StringBuilderapproach is orders of magnitude faster for looped concatenation.
Conclusion
For simple, non‑looped string concatenation, using the
+operator is concise and performs as well as
StringBuilder.
For concatenation inside loops, prefer
StringBuilderto avoid excessive object creation and achieve better performance.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.