String vs. StringBuilder
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
String and StringBuilder both work with text in Java, but they optimize for different constraints. String is immutable, which makes it safe and predictable, while StringBuilder is mutable and efficient for iterative text construction. Picking the wrong type in hot paths can create avoidable allocation and garbage collection overhead.
Why String Exists as an Immutable Type
A String value cannot change after creation. Concatenation creates a new object:
Immutability brings major benefits:
- thread-safe sharing without extra locking,
- stable behavior when used as map keys,
- compatibility with the JVM string pool.
Because the contents never change, two parts of your program can safely reference the same string instance.
Where StringBuilder Provides Real Gains
StringBuilder uses a growable internal buffer, so repeated appends reuse storage instead of creating many temporary objects.
This pattern is usually much faster than repeated + inside loops, especially when building large payloads such as CSV rows, SQL statements, template output, or log lines.
Concatenation and Compiler Behavior
Not every + is a performance bug. The Java compiler often rewrites simple concatenations into builder logic under the hood.
For short expressions this is fine and often clearer. The problem appears when concatenation happens repeatedly in loops or recursive builders, where temporary object creation scales with iteration count.
Capacity Management in Hot Paths
If you can estimate final text size, pre-size the builder to reduce buffer resizing.
Reducing reallocation can improve throughput and smooth latency under load.
Threading Considerations
StringBuilder is not synchronized. If multiple threads mutate one instance, behavior is unsafe. String avoids this issue because it is immutable.
If synchronized mutation is required, Java has StringBuffer, but modern code typically keeps builders thread-confined instead of sharing mutable state.
Example safe pattern:
Each call creates a local builder, so no cross-thread mutation occurs.
API Design Guidance
Expose immutable String values at module boundaries and use builders inside implementation details. This gives consumers a stable contract while preserving internal performance.
In other words:
- input and output types should usually be
String, - intermediate composition should usually be
StringBuilder.
This keeps public APIs simple and avoids leaking mutable implementation details.
Measure with a Microbenchmark
When performance matters, run a benchmark that reflects your workload. A rough comparison:
For large n, the builder approach usually wins by a wide margin.
Common Pitfalls
- Using
+in large loops and generating excessive temporary strings. - Refactoring every short concatenation to
StringBuilder, reducing readability without measurable gain. - Sharing one builder across threads and creating data races.
- Forgetting to call
toString()before returning final output. - Ignoring builder initial capacity in heavy text-generation paths.
Summary
- '
Stringis immutable and ideal for stable, shareable text values.' - '
StringBuilderis mutable and better for iterative text construction.' - Short one-off concatenations with
+are often acceptable. - Loop-heavy or large payload generation should favor
StringBuilder. - Benchmark real workloads before making broad performance claims.
Related reading
- StringBuilder vs String concatenation in toString() in Java
- String.equals versus ==
- String.Join vs. StringBuilder which is faster?
- Strings as Primary Keys in MYSQL Database
- String.format to format double in Java
- String's Maximum length in Java - calling length method
- string.ToLower and string.ToLowerInvariant
- StringWriter or StringBuilder

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.