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.
3
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.
3
StringBuilder was added at a point (Java 1.5) to be a better and faster StringBuffer and the compiler uses it under the hood to implement the +
operator on Strings.
This means that by using StringBuilder you cannot make your code run on JVM’s older than when the class was introduced. This would be a problem to us, for a while yet. If you always run the latest, you don’t need to care.
I would not go through the optimization process you go through, though for the following reasons.
- Outside tight loops the advantage is negligible. Unless it explicitly shows up as a hotspot in a profiler, I wouldn’t bother.
- Changing code may introduce errors, and you must retest your application thoroughly. That may be a lot more expensive than living with a synchronized class in a non-synchronized setting.
2