Tuesday 25 February 2014

Why not to use + operator for String concatenation ?

It is not a good practice to use + operator for string concatenation because of performance overhead.

For example :--

String fruit  = "Apple";

fruit = fruit + "world";

As Strings are Immutable so either StringBuffer (JDK 1.4) or StringBuilder (JDK 5.0) objects are created internally to perform this concatenation.

When +  used for String concatenation, following steps happens internally for above example :--

1. StringBuffer (JDK 1.4)/StringBuilder (JDK 5.0) object is created internally.
2. "Apple" String  referenced by fruit is copied to newly created StringBuffer/StringBuilder object.
3. Then "world" String is appended to above StringBuilder/StringBuffer object.
4. The result is converted back to String object.
5. fruit reference is made to point to that new String.
6. Old String that fruit references earlier is made NULL.

 Hence a single concatenation using + operator involves uses so many steps, hence it is considered a performance hit. Instead of using + operator, use concat() method.
   

No comments:

Post a Comment