Wednesday, June 13, 2012

difference between StringBuilder and StringBuffer?

StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? 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.
  • Use the new StringBuilder wherever possible.

Other than that, the two classes are remarkably similar with compatible API. It seems the author just copied to, 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( s)
Note the above javadoc still refers to StringBuffer where it should be StringBuilder.

2 interesting methods in StringBuilder or StringBuffer are reverse() and equals(Object):
  • reverse() method modifies the current this StringBuilder/StringBuffer, and also returns itself. More details in Reverse a String with StringBuilder or StringBuffer
  • equals(Object) method is not implemented (overridden) in StringBuilder/StringBuffer. So comparing 2 instances of the same content will return false. Also there is no equalsIgnoreCase() method on StringBuilder/StringBuffer. However, toString() is implemented to return a string representing the data in this StringBuilder/StringBuffer.

    No comments:

    Post a Comment