StringBuffer vs StringBuilder

Naveen AnamaneniUpdated · 4 min read

StringBuffer and StringBuilder look identical: same methods, same results. They differ in one thing only: StringBuffer locks itself on every call so several threads can use it safely, and StringBuilder doesn't. That single difference decides which you should use, and the answer for almost all new code is StringBuilder.

One Difference

Same methods; only the lock differs

You can confirm it by asking Java whether the append methods are synchronized:

Locks.java▶ Try it
import java.lang.reflect.Modifier;
 
public class Locks {
    public static void main(String[] args) throws Exception {
        int buffer = StringBuffer.class.getMethod("append", String.class)
            .getModifiers();
        int builder = StringBuilder.class.getMethod("append", String.class)
            .getModifiers();
        System.out.println("StringBuffer.append synchronized: "
            + Modifier.isSynchronized(buffer));
        System.out.println("StringBuilder.append synchronized: "
            + Modifier.isSynchronized(builder));
    }
}
Output
StringBuffer.append synchronized: true
StringBuilder.append synchronized: false

This uses reflection (covered later in the course) to read the method's modifiers. The point is simple: the lock is the only real difference.

Why StringBuilder Is Faster

Taking and releasing a lock costs a little time on every call, even when no other thread is around. In one timing run of 5 million single-character appends, StringBuffer took about 21 ms and StringBuilder about 14 ms. Modern JVMs remove much of the locking cost when they can prove only one thread uses the object, so the gap is usually small; but StringBuilder is never slower.

String, StringBuffer and StringBuilder

StringStringBufferStringBuilder
Mutable?NoYesYes
Thread-safe?Yes (immutable)Yes (synchronized)No
Speed for many changesSlowFastFastest
equals compares text?YesNoNo
SinceJava 1.0Java 1.0Java 5
Use forValues you store, compare and shareText built by several threads togetherText built step by step, in one thread

Common Mistakes

Picking StringBuffer by habit from old tutorials. Default to StringBuilder.

Sharing a StringBuilder field between threads. That's the one case it breaks; use a local builder per call, or StringBuffer.

Using either one when + on one line would do. Builders are for many steps.

Interview Corner

What is the difference between StringBuffer and StringBuilder?

Both are mutable sequences of characters with the same API. StringBuffer, from Java 1.0, synchronizes its methods, so it's thread-safe but slightly slower. StringBuilder, added in Java 5, isn't synchronized, so it's faster but must not be shared between threads without external locking. StringBuilder is the default choice for building strings in single-threaded code.

Compare String, StringBuffer and StringBuilder.

String is immutable and thread-safe by nature, best for values. StringBuffer is mutable and synchronized, for text modified by multiple threads. StringBuilder is mutable and unsynchronized, the fastest choice for building text in one thread. Only String overrides equals to compare content and uses the string pool.

Practice

  1. Easy: Replace every StringBuffer in the "StringBuffer in Java" examples with StringBuilder and check that the single-threaded output doesn't change.
  2. Harder: Write a method that builds a comma-separated line from an int[], using a local StringBuilder. Explain why it's thread-safe even if many threads call the method at once.

Quick check: StringBuffer vs StringBuilder

4 questions
1Which one is synchronized?
2Which should you use to build text inside one method?
3Which was added in Java 5?
4Do StringBuffer and StringBuilder have the same methods?

Key Takeaways

Was this tutorial helpful?

Lesson 201 of 482