Friday, February 4, 2011

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

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;

ANS) 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.

No comments:

Post a Comment