• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

What’s Being Compared

Java provides three classes for working with character sequences: immutable String, thread-safe mutable StringBuffer, and non-thread-safe mutable StringBuilder. Understanding when to use each is critical for writing correct and performant code.

The Core Tension

The tradeoff is between safety and performance. Immutability (String) is the safest but creates garbage under modification. Synchronization (StringBuffer) adds thread safety but incurs overhead. StringBuilder drops synchronization for speed but is unsafe in shared contexts.

Comparison

DimensionStringStringBufferStringBuilder
MutabilityImmutableMutableMutable
Thread safetySafe (immutable)Safe (synchronized)Unsafe
PerformanceSlow for modificationModerate (sync overhead)Fastest
Use caseFixed text, constants, keysLegacy code (Java 1.0)Dynamic building (Java 1.5+)
Concatenation in loopsO(n²) garbageO(n) bufferO(n) buffer

When to Use String

  • The value never changes after creation
  • As map keys (immutability guarantees hash stability)
  • Thread-safe sharing without synchronization
  • Short, fixed strings

When to Use StringBuilder

  • Building strings dynamically in a single-threaded context
  • Inside methods (local variable, no sharing)
  • String concatenation in loops (compiler translates + to StringBuilder anyway)

When to Use StringBuffer

  • Mutable string building in a shared, multi-threaded context
  • Legacy code that already uses it
  • Rare — StringBuilder is almost always preferred in modern code

The Insight

The Java compiler itself prefers StringBuilder — "a" + "b" + "c" is compiled to new StringBuilder().append("a").append("b").append("c").toString(). There is almost never a reason to use StringBuffer in new code. The real choice is between String (immutable, safe) and StringBuilder (mutable, fast).

Connections