StringBuffer vs StringBuilder

 

According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage.

Their key differences in simple term:

  • StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.
  • StringBuilder has better performance than StringBuffer under most circumstances.

Other than that, the two classes are remarkably similar with compatible API. It seems the author just copied StringBuffer.java to StringBuilder.java, removing all occurrences of “synchronized”.

Here is a little trace left in StringBuilder.readObject method:

/**
* readObject is called to restore the state of the
* StringBuffer from a stream.
*/
private void readObject(java.io.ObjectInputStream s)

Note the above javadoc still refers to StringBuffer where it should be StringBuilder.

Here’s the simple benchmark test

public class Main {
public static void main(String[] args) {
int N = 77777777;
long t;

{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = N; i --> 0 ๐Ÿ˜‰ {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}

{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = N; i --> 0 ๐Ÿ˜‰ {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
}
}

A test run gives the numbers of 2241 ms for StringBuffer vs 753 ms for StringBuilder [the results may vary]

 

StringBuffer vs StringBuilder
Rate this post

Leave a Reply