• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the best way to do string concatenation?

 
Franco Finstad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Arvind Dua
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Junilu Lacar
Bartender
Pie
Posts: 7306
45
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic