- 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 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.
2 interesting methods in StringBuilder or StringBuffer are
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