StringBuffer and Comparison

String vs StringBuilder vs StringBuffer

StringStringBuilderStringBuffer
Mutablenoyesyes
Thread-safeyes (immutable)noyes (synchronized methods)
Speedslow for repeated changesfastestslower than StringBuilder
SinceJava 1.0Java 5Java 1.0
Use forfixed text, keys, constantsbuilding text in one thread (almost always)legacy code; shared buffer across threads

Same API

Example

StringBuffer has the same methods as StringBuilder; only the synchronisation differs.

public class Main {
    public static void main(String[] args) {
        StringBuffer log = new StringBuffer();
        log.append("[INFO] ").append("Server started");
        log.append(" on port ").append(8080);
        System.out.println(log);
        System.out.println("capacity >= length: " + (log.capacity() >= log.length()));
    }
}

Output

[INFO] Server started on port 8080
capacity >= length: true

Measuring the Difference

Example

Concatenating with + in a loop copies the whole string each time. The exact timings vary, so this program prints only which approach was faster.

public class Main {
    public static void main(String[] args) {
        int n = 20000;

        long t1 = System.nanoTime();
        String s = "";
        for (int i = 0; i < n; i++) {
            s += "x";
        }
        long plusTime = System.nanoTime() - t1;

        long t2 = System.nanoTime();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append("x");
        }
        long builderTime = System.nanoTime() - t2;

        System.out.println("Both lengths equal: " + (s.length() == sb.length()));
        System.out.println("StringBuilder faster: " + (builderTime < plusTime));
    }
}

Output

Both lengths equal: true
StringBuilder faster: true

Note: A single expression like "Hi " + name + "!" is fine; the compiler optimises it. The problem is += inside loops.