Normally use the String concatenations using :  +, StringBuffer.append(), String.concat(). We always think that using ‘+’ operator for String Concatenation is slow.  This is true but not always.

For Ex: String str = “This”  + “is” + “for test”; //This will be faster if these constants are fetched from String Pool

The above example is really fast as Java will use single constant to replace all these literal values and replace this constant with a direct assignment operation. This approach is definitely faster than using StringBuilder.

Another approach which gives worst performance while concatenating strings is writing code as follows

String str = “”;
for (int i=0; i<200; i++) {
     str += i;
}

In the above example the StringBuilder object is created implicitly to do the concatenation internally and so causes overhead. The optimized code is

StringBuilder strBuilder = new StringBuilder();
for (int i=0;i<200;i++) {
     strBuilder.append(i);
}
String str = strBuilder.toString();

We can either use StringBuffer or StringBuilder to concatenate strings. StringBuffer is thread safe while StringBuilder is not. If we are using  the object str in a local method then it is better to use StringBuilder because it is faster. If the object is getting modified by many threads then it is always better to use StringBuffer to avoid concurrency issues.

Here is a sample program to compare the String concatenation operations, and the result of running the iterations for 10000 times.

************* Test Output ****************
Time taken for StringBuilder = 10 ms
Memory taken for StringBuilder = -77800 bytes

Time taken for '+' Operator = 894 ms //More time
Memory taken for '+' Operator = -5830752 bytes

Time taken for Concat method = 184 ms
Memory taken for Concat method = 165298256 bytes //More memory

Time taken for StringBuffer = 2 ms //Less Time
Memory taken for StringBuffer = 0 bytes //Less Memory
******************************************

Recommendation: Preferably use StringBuffer for all your String concatenation operations, its faster and consumes less memory.

发表评论