In a production web application, my fellow programmers used StringBuffer everywhere. Now I am taking care of application development and corrections. After reading StringBuilder and StringBuffer I have decided to replace all the StringBuffer code with StringBuilder because we don't need thread safety in our data beans.
For example: (In each data bean I can see the use of StringBuffer)
@Override
public String toString() {
StringBuffer sb = new StringBuffer();// replace it from StringBuilder
sb.append(" ABCD : ").append(abcd);
sb.append(", EFGH : ").append(efgh);
sb.append(", IJKL : ").append(ijkl);
}
We create a separate data beans for each session/request. A session is used by a single user no other user can access it.
Should I consider other points before migrating?
If there is a single thread (no waiting threads/no new thread will be looking for object lock), it performs equally with either StringBuffer or StringBuilder. I know in the case of StringBuffer, it takes time to take the object lock but I want to know if there is any performance difference between them except the hold/release of the object lock.
sbas a local variable like in your example, then thread-safety doesn't matter at all. Even if a thousand threads simultaneously entered the method, each would have its own call stack with its own local variables. The StringBuilders would never interfere with each other.StringBuffer. I've never seen code like that but I'm almost sure it's a bad design from a multithreading perspective. Since I think synchronizing thread along theStringBufferinterface is a bad idea I think this class shouldn't exist and one should always useStringBuilder. As others already mentioned,StringBufferexists for historical reasons.