Fundamentals 6 min read

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.

macrozheng
macrozheng
macrozheng
Why ‘+’ Can Beat StringBuilder in Java: Benchmarks and Best Practices

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaperformanceBenchmarkstringbuilderString concatenation
macrozheng
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.