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 StringBuilder is always faster than the + operator for concatenating strings. Since JDK 5, the Java compiler automatically rewrites + concatenations into StringBuilder calls, so the two approaches generate identical bytecode.
Benchmark: Simple Concatenation
A test class StringTest contains two methods—one using + and one using StringBuilder —each called 100,000 times in a JUnit test. The results are:
testStringConcatenation01ByPlus,拼接字符串100000次,花费33秒
testStringConcatenation02ByStringBuilder,拼接字符串100000次,花费36秒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 StringBuilder instance each iteration, leading to much higher overhead. A benchmark comparing looped + versus a single StringBuilder instance shows a dramatic performance gap.
testLoopStringConcatenation03ByPlus,拼接字符串10000次,花费463秒
testLoopStringConcatenation04ByStringBuilder,拼接字符串10000次,花费13秒The StringBuilder approach 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 StringBuilder to avoid excessive object creation and achieve better performance.
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.
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.
