Java StringBuilder, StringBuffer and String Concatenation

String assembly sits inside many ordinary backend operations: constructing JSON responses, building log messages, joining identifiers and formatting validation errors. Yet the choice between StringBuilder, StringBuffer and + is often reduced to a rule of thumb, even though the result depends on the Java compiler, JVM version, payload size and execution pattern.

Those differences matter for teams serving Australian customers from AWS regions in Sydney and Melbourne. Local data-residency expectations can constrain deployment options, while Boxing Day retail traffic and end-of-financial-year processing can expose allocation pressure. A useful comparison therefore needs to consider more than a single execution-time figure.

What Each String-Building Approach Does

Java strings are immutable. An operation such as first + " " + last produces a new string value rather than changing either operand. The compiler and JVM can optimise this pattern, but each concatenation operation may also involve intermediate values, copying and additional garbage collection work.

StringBuilder maintains mutable internal storage. Calling append() writes into that storage and can avoid creating a new string for every addition. It is not synchronised, making it the usual choice when one thread owns the builder throughout its lifetime. The builder itself does not need to become thread-safe merely because the final string will be published to other threads.

StringBuffer also provides mutable append operations, but its relevant methods are synchronised. This makes individual operations thread-safe at the cost of locking. The overhead may be modest in a low-contention program, yet a shared builder can become a contention point when many worker threads append concurrently. Correctness also depends on how the complete sequence is assembled; synchronising individual calls does not automatically make a compound operation atomic.

Why Java Versions Change the Result

Historically, javac translated string concatenation into bytecode that created and manipulated a StringBuilder. Modern compilers commonly use invokedynamic and StringConcatFactory for expressions with non-constant operands. This moves the choice of concatenation strategy towards runtime execution and allows the JIT compiler to inline specialised implementations.

Those implementations can be surprisingly effective. The JIT may remove unnecessary intermediate strings, adjust allocation size or apply locality improvements after the method becomes hot. Measurements taken on Java 8 therefore should not be assumed to predict Java 17, Java 21 or a newer release. Even two services using the same source code may behave differently if they were compiled with different --release settings or run on different JVM builds.

Memory behaviour has changed as well. Compact strings introduced in Java 9 allow a String to store Latin-1 characters in a byte array rather than a full character array. This benefits many business identifiers and log messages containing ordinary English text. It does not remove the allocation cost of creating a new immutable result, but it changes the size of each allocation and the pressure it places on the heap.

Comparing Execution and Memory Costs

A fair comparison examines throughput, allocation and contention rather than treating one method as universally fastest. The following comparison highlights the distinct operating characteristics of each approach for developers evaluating performance trade-offs.

Approach Mutability Thread safety Common use Main performance consideration
StringBuilder Mutable No Loops and local assembly of larger values Low overhead when owned by one thread; can retain excess capacity
StringBuffer Mutable Yes for synchronised operations Rare cases involving a deliberately shared builder Lock overhead and possible contention
+ concatenation Produces immutable results Safe to publish the completed result Short expressions and many modern compiler patterns Compiler and JVM optimisation can make it efficient; intermediate values may still consume memory

These distinct behaviours demonstrate that string manipulation efficiency relies heavily on the surrounding execution context.

A loop that appends thousands of fragments exposes the difference between repeated immutable results and a reusable buffer most clearly. In a simple expression containing two or three operands, however, + may be just as fast or faster because the generated code is specialised for that exact operation.

Allocation profiling should accompany timing results. A faster method that produces considerably more short-lived objects can increase young-generation collection activity and add latency later in a request. This is particularly relevant to services with tight heap limits or high allocation rates. It also explains why a microbenchmark can report excellent throughput while a production service still shows unstable tail latency under concurrent load.

The useful question is therefore not which syntax has the lowest benchmark time. It is which approach produces the least total work for a representative workload while preserving predictable behaviour under real concurrency.

Building a Trustworthy Benchmark

JMH is a suitable starting point because it handles warm-up, dead-code elimination and repeated measurement more carefully than a conventional unit test. Each approach should have a separate benchmark method, with realistic inputs created during setup rather than inside the measured operation. Results, rather than discarded temporary values, should be returned or passed to a blackhole so the compiler cannot remove the work.

The benchmark should record the JVM version, JVM flags, processor, operating system and relevant compiler settings. Measurements can vary between laptop hardware, a local CI worker and an Australian production host, so hiding that context makes the numbers difficult to interpret. Benchmark methods should also run long enough for the JIT compiler to reach a stable state.

Before results are circulated, the site's policy notices provide the reference for publication and measurement expectations. In particular, a credible result needs reproducible parameters rather than a headline taken from one uncontrolled execution.

Representative inputs matter more than arbitrary sizes. A service in Brisbane processing domestic parcel identifiers may see short ASCII strings, while a platform in Perth might handle longer payloads assembled from several services. Give the benchmark a quick squiz with production-shaped data, including empty values, occasional Unicode and the largest common response. Separately, use a load test to measure the complete REST endpoint because database calls, serialisation and network latency often obscure the cost of string construction.

When Plain Concatenation Makes Sense

The + operator remains a good choice for short, straightforward expressions. It is concise, easy to review and often generates efficient code on modern JVMs. A compile-time constant expression can be folded directly into the class file, while expressions involving runtime values can use the specialised invokedynamic path. Neither case requires developers to manage a builder manually.

Plain concatenation also works well when the string is created once and discarded. Optimising a builder for a value that will immediately become garbage may add complexity without producing a meaningful benefit. In code that handles identifiers, short labels or status messages, readability can outweigh an insignificant execution-time difference.

An explicit StringBuilder is generally clearer for loops and values whose final size is unknown or large. It lets the JVM reuse internal storage instead of constructing a separate immutable result for each iteration. When joining a known collection with a separator, String.join or a collector may express the intent more accurately than either approach, although their implementation and allocation behaviour should still be measured if the workload is substantial.

The surrounding work frequently matters more. Formatting a number, boxing a value, invoking a date-time formatter or serialising an object can cost more than the concatenation itself. Profiling before changing code prevents a local string optimisation from distracting the team from a larger bottleneck.

Thread Safety and Concurrent Backend Workloads

The common recommendation to use StringBuffer whenever multiple threads are involved is too broad. If each request or asynchronous task creates its own builder, there is no shared mutable state and no need for locking. Publishing the completed immutable string then lets other threads read it safely.

A shared StringBuffer provides synchronisation around its individual methods, but it does not make higher-level workflows automatically correct. A sequence such as checking the length and then appending based on that length can still race unless the complete sequence is guarded by the same lock. Under heavy contention, monitor overhead can also affect throughput and tail latency.

Modern JVMs have improved uncontended locking, yet lock contention remains a genuine issue when many threads operate on the same object. Local ownership is usually the simpler design: create the builder inside the request handler, finish the message, convert it to an immutable string and pass that result into any asynchronous pipeline. This pattern works well for Java services distributed across Australian teams because it avoids coordinating access to a distant, shared builder.

Turning Findings into an Engineering Decision

Start with the semantic requirement. Use StringBuilder for local, potentially substantial assembly; use StringBuffer only when a shared mutable builder is genuinely required and its compound operations are correctly synchronised; use + for clear, short expressions where modern compiler optimisation is acceptable.

Then evaluate the cost in the context of the deployed service. Heap limits, request concurrency and the latency target determine whether extra allocations or lock contention are material. Australian cloud invoices commonly show costs in Australian dollars, making small efficiency gains relevant when they reduce compute or autoscaling expenditure across a busy trading period.

The next concrete step is to add one JMH module to the service repository, with three benchmarks over a production-shaped payload, pinned to the same JDK used in deployment and with the resulting measurements stored beside the deployment configuration.