The Java standard library provides StringBuilder for the highly efficient stitching of Java string. StringBuilder provides an API compatible with StringBuffer, but with no guarantee of synchronization.

Java StringBuilder VS StringBuffer

Instances of StringBuilder are not safe for use by multiple threads. For synchronization, then the better option is StringBuffer.

So, if in the single-thread cases, it is recommended to use StringBuilder in preference to StringBuffer, for StringBuilder is much faster in most implementations.

For example:

String s = "";
for (int i = 0; i < 1000; i++) {
    s = s + "," + i;
}

In this example, although it can stitch strings directly in a loop. But, each loop creates a new string object and then throws away the old string. In this way, most strings are temporary objects, which not only wastes memory but also affects the efficiency of GC.

StringBuilder sb = new StringBuilder(1024);
for (int i = 0; i < 1000; i++) {
    sb.append(',');
    sb.append(i);
}
String s = sb.toString();

Then, in this single thread case, you can try to use StringBuilder to do the job. StringBuilder is a mutable object and can pre-allocate buffers so that StringBuilder when new characters are added to it, no new temporary object is created. By that, it runs faster.

Run the code to compare the time cost:

public class Main {
    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder(1024);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            sb.append(',');
            sb.append(i);
        }
        String string = sb.toString();
        long time1 = System.currentTimeMillis() - start;
        System.out.println("Time cost: " + time1);
        System.out.println(string);

        
        long start2 = System.currentTimeMillis();
        String ss = "";
        for (int i = 0; i < 10000; i++) {
            ss = ss + "," + i;
        }
        long time2 = System.currentTimeMillis() - start2;
        System.out.println("Time cost: " + time2);
        System.out.println(ss);

    }
}

Output

Time cost: 12


Time cost: 234


Note that: For ordinary string +operations, it does not need to rewrite it as using StringBuilder, as the Java compiler automatically encodes  + multiple consecutive operations into StringConcatFactoryoperations at compile time. At runtime, StringConcatFactorystring concatenation operations are automatically optimized for array copying or StringBuilderoperations.

The chained operation of StringBuilder

In the StringBuilder source code, we can find that the key to chain operation is that the defined append()method will return this, so that other methods of itself can be constantly called.

public class Main {
    public static void main(String[] args) {
        var sb = new StringBuilder(1024);
        sb.append("Etbye")
          .append(".")
          .append("com")
          .insert(0, "Hello, ");
        System.out.println(sb.toString());
    }
}

Output:

Hello, Etbye.com

Exercise

Similarly to StringBuilder, try to design a counter that can be incremented by using the chain operation.

Sample code

public class Main {
    public static void main(String[] args) {

        Adder adder = new Adder();
        adder.add(3).add(7).inc().add(2);
        System.out.println(adder.value());
    }
}


class Adder {
    private int sum = 0;

    public Adder add(int i) {
        sum += i;
        return this;
    }

    public Adder inc() {
        sum++;
        return this;
    }

    public int value() {
        return sum;
    }

}

Output: 13

summary

  • StringBuilderis a mutable object, used to efficiently stitch strings;
  • StringBufferis the thread-safe version of StringBuilder, however, rarely used now.
  • StringBuildercan support chained operations, the key to achieving chained operations is to return to the instance itself;

Read further: https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/StringBuilder.html