Tuesday, March 27, 2012

Using String Buffer to optimize string concatenation

It is always better in performance to use String Buffer in string concatenation over using + . We can consider a code segment as follows where + is used to concat a string. If one and two a two defined strings; 


String s = one+two;

This is similar to ;

StringBuffer buf = new StringBuffer(one);
buf.append(two);
String s = buf.tostring();

In a situation as above, it doesn't make a difference using StringBuffer over + in string concatenation. Let's consider a situation where a string concatenation happens within a loop as given below.


String xx;
for ( int i = 0; i < name.length(); i++ )
{
xx = String.valueOf( name.charAt( i ) );
tempName = tempName + xx;
}
              return tempName;




This will end up creating  name.length() number of string objects in memory. If the following code segment is used instead, it will enhance the performance significantly.


String xx;
        StringBuffer buf = new StringBuffer();
for ( int i = 0; i < name.length(); i++ )
{
xx = String.valueOf( name.charAt( i ) );
                        buf.append( xx );

}
                       tempName= buf.toString();
return tempName;

No comments:

Post a Comment