When to Use StringBuilder or StringBuffer in Java

asyncjavastringssynchronization

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.

Best Answer

The only difference between the two is the synchronization used in StringBuffer. The overhead of synchronization is not huge in the grand scheme of things, but it is significant relative to the StringBuilder methods that don't have them. The JVM is doing work that it wouldn't otherwise have to do--especially with only one thread, etc.

If your code works and people aren't complaining about performance, I wouldn't worry about it. You aren't going to get a lot of bang for your buck. However, if you are writing new code, or are updating code that uses StringBuffer, I'd suggest converting them StringBuilder at the same time.

Related Topic