String concatenation and StringBuffer
In Java, String concatenation operator (+) is internally implemented
using StringBuffer.
For Example,
String str = “Hello” + “World”;
Would be executed as,
String str = new StringBuffer().append(“Hello”).append(“World”).toString();
First an empty StringBuffer will be created and then operands of
the + operator would be appended using append method of the StringBuffer.
Finally toString() method of the StringBuffer would be called to
convert it to string object and the same will be returned.
String concatenation using this approach is very expensive in nature,
because it involves creation of temporary StringBuffer object. Then
that temporary object’s append method gets called and the
resulting StringBuffer should be converted to back String representation
using toString() method.
When to use String and when StringBuffer?
If there is a need to change the contents frequently, StringBuffer
should be used instead of String because StringBuffer concatenation
is significantly faster than String concatenation.
|