StringBuffer Or String For Concatenations?
Written on 9:33 PM by ronald
There are two classes in Java which are being used for manipulation of Strings.
As a junior developer, i am always using String. The only reason why i use StringBuffer is only to make my code seen more clean. That was what i thought so until recently when i tried to resolve some performance issue with the uploading of files in my web application.
I have the below string operation
String strList = strList + randomNo;
Depending on the size of the uploaded file, the strList could get very long in terms of ten of thousands of strings concatenated together.
Now that was really a problem. User could get timeout exception when they upload big files. And initally i thought it was because of the validation checks i am doing for the file.
Until i googled and saw this article. Javaworld: StringBuffer versus String
after i change to using StringBuffer, the performance increased alot.
StringBuffer strList = new StringBuffer();
strList.append(randomNo);
You all can look through this article for a detailed explaination. But the conclusion is that StringBuffer should always be used for concatenation and we can always convert it back to string using strList.toString()

Please have a look at StringBuilder also:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html
Yeah. I just look through the documentation so StringBuilder is even faster than StringBuffer huh. Too bad didn't find any speed comparisons between these two classes.
Thanks alot though
And that's a pretty simple example. Imagine you have a cycle (for or while) concatenating several values. If you use String, then you're creating several objects, instead of just one (the StringBuilder or StringBuffer).
This might be of interest:
http://java.sun.com/developer/technicalArticles/Interviews/community/kabutz_qa.html
It does contradict your findings though. Which version of Java were you using for your webapp?
One of my new favorite is String.format() - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)
It's very C style like.
e.g. String.format("%s %s",
"ABC", "DEF");