Not many people know that StringBuffer is synchronized.
Due to synchronized methods, a single StringBuffer instance can be safely manipulated from many threads at once, a feature rarely needed in the majority of cases where StringBuffer is used as a temporary variable.
To control access to methods requires object locking in StringBuffer which is slower.
So Java 1.5 provides an identical but unsynchronized StringBuilder class. If it is safe to use Java 1.5, StringBuilder should always be used in preference to StringBuffer – except for code that requires synchronized access to the buffer.
public String toString()
{
StringBuffer buf = new StringBuffer();
:
return buf.toString();
}
Can now be written:
public String toString()
{
StringBuilder buf = new StringBuilder();
:
return buf.toString();
}
There is no need to go through existing code and do wholesale replacements of StringBuffer with StringBuilder unless there is a known problem with it. Even then, problems will more likely be in design rather than the fault of StringBuffer.