Sunday, September 18, 2011

String concatenation

There are various ways of implementing String concatenation in Java. Here are three means which one would often hear and ponder on their differences with respect to performance implications of using them

String – Concatenation of two string objects creates a new object internally. Use String objects in places where concatenation requirement is very less. (String object is immutable, i.e. value stored in the String object cannot be changed)

StringBuffer – Is synchronized, which means it is thread safe and hence we can use it to implement threads for your methods

StringBuilder – Added in Java 5. Identical in all respects to StringBuffer except that is NOT synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble (Not thread safe). For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.

Note: StringBuffer/StringBuilder is mutable.

No comments:

Post a Comment