Java Quiz: Why StringBuilder Should be Used Instead of StringBuffer?
By Angsuman Chakraborty, Gaea News NetworkSaturday, 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.
August 24, 2008: 9:59 am
Here is an article I wrote on the subject: Cheers |
August 24, 2008: 12:06 am
@Porter |
Burt |
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? |
Angsuman Chakraborty