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()
