What is the best way to do string concatenation? I read that using "+" on a string object uses StringBuffer behind the scenes so it seems that using StringBuffer explicitly is unecessary. So, should I do: myString + "foo" + "bar"; or myStringBuffer.append("foo").append("bar"); Any help is appreciated.
Joined: Sep 29, 2000
If you do the first you will end up with a String object that is immutable. If you do the second you will end up with a StringBuffer object that is mutable. Which do you WANT?
"JavaRanch, where the deer and the Certified play" - David O'Meara
Joined: Mar 28, 2003
Besides what Cindy said another criteria for deciding whether to use a StringBuffer or String concatenation is the number of String Objects you need to concatenate. If it is only 2 both are equal in terms of performance . But if the number of Strings you want to concatenate is more, I will certainly prefer StringBuffer because everytime I concatenate two Strings a new Object is created( because String objects are immutable and cannot be modified) but if its a StringBuffer, the same Object is modified to hold the concatenated String and no new Objects are created. Hope this helps !! [ May 22, 2003: Message edited by: Arvind Dua ]
You might want to consider readability before trying to second guess the compiler's optimization capabilities. A succession of append()s to a StringBuffer would probably throw another programmer off at first glance. Try to write clear code first; use a profiler to find bottlenecks. [ May 22, 2003: Message edited by: Junilu Lacar ]