• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String Concatenation - StringBuffer.append Vs. String = String + String

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
While performing concatenation of strings, is it OK to use StringBuffer or String.
Which of the following syntaxes is more efficient ? Why ?
StringBuffer sbName=new StringBuffer();
sbName.append(fName);
sbName.append(lName);

(OR)
String sName=new String();
sName=sName+fName;
sName=sName+lName;
Thanks
Greg
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Using StringBuffer is much more efficient than using '+' to concatenate strings because the '+' operator creates a new String instance each.
Just remember that if you have the following statement...
String s = "a" + "b" + "c";
...the compiler will actually optimize this code segment for you and use StringBuffer.append() automatically. The compiler will only do this for a single statement at a time; it will not combine statments.
StringBuffer will always be quicker than '+' because it's a method invocation as opposed to a new object instantiation.
Try it out yourself. Create a loop that appends a string to itself 100 times using '+'. Then do the same thing using StringBuffer.append() and compare the times. You'll be surprised how much faster append() is.
SAF

[This message has been edited by SAFROLE M3 (edited July 05, 2001).]
 
Attractive, successful people love this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic