Java Quiz: Why StringBuilder Should be Used Instead of StringBuffer?

By Angsuman Chakraborty, Gaea News Network
Saturday, August 23, 2008

First tell me what is the best way to concatenate large number of String objects? Is it a + b?

Most Java developers know not to use a + b (+ operator) because of huge performance problems, they use StringBuffer instead. In fact I did some tests in the past which confirms this folklore. However some of you may not know there is new kid on the block - StringBuilder.

java.lang.StringBuilder is java.lang.StringBuffer’s cousin (like java.util.HashMap is to java.util.Hashtable or java.util.HashSet is to java.util.Vector) but without the synchronization overhead. Unless you need to concatenate a String from multiple Threads, you are likely to get better performance with StringBuilder.

Filed under: How To, Java Software, Programming

Tags:
Discussion
August 29, 2008: 9:27 am

Thanks for the link

August 24, 2008: 9:59 am

Here is an article I wrote on the subject:
StringBuffer vs. StringBuilder performance comparison
You might find it useful.

Cheers

August 24, 2008: 12:06 am

@Burt
Yes, ArrayList, my bad. Thanks.

August 24, 2008: 12:06 am

@Porter
I ran a benchmark, you too can run one if you like. Try using + for large concatenation and it really sucks. Yes, I am talking about large amount of Strings like say in a for loop - “best way to concatenate large number of String objects”. I thought I was very clear on that.


Burt
August 23, 2008: 7:15 pm

You mean “java.util.ArrayList is to java.util.Vector”.


Porter
August 23, 2008: 1:38 pm

Can we stop with the pernicious and erroneous assertion that using the ‘+’ operator to concatenate strings is slow.

Run a benchmark first.

For common cases using the + operator to build a string is no slower than the old style String buffer approach. It hasn’t been since around Java 1.4.2 or 1.5. It is slower for large concatenations - assembling say 1000 or more strings into one larger string…

https://paulbarry.com/articles/2007/03/15/java-string-concatenation

https://www.ibm.com/developerworks/java/library/j-jtp04223.html

https://www.javaworld.com/javaforums/showflat.php?Cat=2&Number=94239&an=0&page=0

OK?

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :