Java Tip #1: Use StringBuilder instead of StringBuffer

As promised last time I'm presenting here the first in a series of Java Tips. To start easy I'll begin with one of the simplest tip to implement.


Use StringBuilder instead of StringBuffer.



  StringBuffer str = new StringBuffer();
  String x = str.toString();


  StringBuilder str = new StringBuilder();
  String x = str.toString();


Small performance gain. StringBuilder is a 1:1 drop-in replacement for the StringBuffer class. The difference is that the StringBuilder is not thread synchronized and therefore performs better on most implementations of Java. Even javac internally translates String x = "foo" + "bar"; into a StringBuilder operation (confirmed with Java 1.6.0_18). A small testcase

public static void main(String[] args) {
    long start = System.currentTimeMillis();
    StringBuffer buffer = new StringBuffer();
    for(int i = 0; i < 1000000; i++) {
    System.out.println("Time lapse using StringBuffer: " + (System.currentTimeMillis() - start) + " milliseconds");

    start = System.currentTimeMillis();
    StringBuilder builder = new StringBuilder();
    for(int i = 0; i < 1000000; i++) {
    System.out.println("Time lapse using StringBuilder: " + (System.currentTimeMillis() - start) + " milliseconds");

using Java 1.6.0_18 shows that StringBuilder is roughly 100% faster than StringBuffer. Although on my machine this testcase keeps below 100ms for both with one million appends so this won't be the magical solution for most of your performance issues.


Even if this tip can be applied in 98% of all cases one has to be sure that the String is used afterwards and the StringBuilder instance does not get passed between several threads. Since StringBuilder is not thread-safe this would be the only case where StringBuffer should be used. And of course it's not the silver performance bullet but just one slice in string-heavy applications.


Similar entries