Friday, July 22, 2005

Overkill of StringBuffer

I have seen so many codes that abuses the StringBuffer. Yes, the StringBuffer was created for String manipulation since String manipulation is a bit of heavy and String is immutable. StringBuffer is synchronized. So please, use this with discretion. If you don't use true-blue String manipulation, do not use (aka abuse) StringBuffer.

In JDK 5.0, there is a new class called StringBuilder. What's the difference between a StringBuffer and a StringBuilder?

I'll answer it in one shot:

StringBuffer is to Vector while StringBuilder is to ArrayList.

Got it?

6 comments:

Anonymous said...

Fortunately StringBuffer and StringBuilder have almost identical performance.

afsina said...

They are same, except StringBuilder is not Thread safe. supposedly a little faster because it's manipulation methods are not synchronized. But nowadays word on street says making methods "synchronized" does not make a performance difference. You can read Azul System's performance predsentation from Java one..

Richard said...

it all depends now on your functionality and design requirements. speed is not really an issue anymore when it comes to synchronized methods and blocks since J2SDK 1.4 and JDK 5 (Tiger)

Rajneesh Garg said...

Check out http://rgarg.blogspot.com/2005/07/java-se-50-whats-difference-between_04.html

afsina said...

"StringBuffer is to Vector while StringBuilder is to ArrayList." is not exactly correct. Yes, Vector is Thread safe and ArrayList is not, but Vector class was not a part of Collections and it has some inconsistent methods comparing with ArrayList. After the introduction of Collections, they imlemented List interface methods within. But still you will see stuff like Elements, Enumerations etc in it. Nowadays many suggests not using Vector and consider it deprecated. You can make an ArrayList ThreadSafe by using Collections.synchronizedList(list).

But, StringBuffer and StringBuilder have exactly the same structure and methods.

Richard said...

Yes, Vector and ArrayList are not comparable, one to one w.r.t. their internal logic because Vector was just a retrofitted class to complement and be an addition to the collections fw. But hey, both implements the same set of interfaces and both forms part of the Collections API set. And from the point of view of the end-user (client program), both are just the same except that one is thread safe, the other isn't.

Yes, Collections.synchronized() can be used to make calls to an ArrayList thread safe. However, when I do multithreaded programs, I'd rather not rely on Collections.synchronized() nor blindly use Vector. I'd see to it that the design addresses this.

Going back to my main point. As I see a lot of misuse of StringBuffer, and I say, use this with discretion. An alternative would be using StringBuilder if you're not going multithreaded.