From: http://anonymous.bokee.com/875294.html
String concatenation operator (+, string concatenations operator); if it is to generate a line of output, or produce a small, fixed-size object + is very suitable, but for large-scale situations; because the string connector is used repeatedly to connect n strings, it requires a square-level time of N. (The string is immutable. When two strings are connected, their content will be copied)
Here is an example to illustrate this :......
+ ------- Code ------------ +
Public class stringpolictive
{
Public static void main (string ARGs [])
{
String S = "ABC ";
Stringbuffer sb = new stringbuffer (100 );
Int Circle = 100000;
Long T1 = system. currenttimemillis ();
For (INT I = 0; I <circle; I ++)
{
S + = "";
}
Long T2 = system. currenttimemillis ();
System. Out. println ("[String] Time: <" + (t2-t1) + "> ");
T1 = system. currenttimemillis ();
For (INT I = 0; I <circle; I ++)
{
SB. append ("");
}
T2 = system. currenttimemillis ();
System. Out. println ("[stringbuffer] Time: <" + (t2-t1) + "> ");
}
}
/**
* Circle = 100
* Result:
* [String] Time: <0>
* [Stringbuffer] Time: <0>
* + --------------------------- +
* Circle = 1000
* Result:
* [String] Time: <15>
* [Stringbuffer] Time: <0>
* + --------------------------- +
* Circle = 10000;
* Result;
* [String] Time: <1, 954>
* [Stringbuffer] Time: <0>
* + --------------------------- +
* Circle = 100000
* Result:
* [String] Time: <1, 526828>
* [Stringbuffer] Time: <15>
*/
+ ------------ End --------------------- +
The time used by the first method is exponential growth, and the second is linear growth. Therefore, if the project is large enough, the performance difference is more significant. Note that the second method allocates a stringbuffer in advance so that it is large enough to accommodate the result string. However, even if you do not know the size of the result string and use a stringbuffer of the default size, it is still 45 times faster than the first method.
So to sum up, in the words of Joshua Bloch: Do not use the String concatenation operator to merge multiple strings unless the performance doesn't matter. Instead, use the append method of stringbuffer, or use other methods, such as using character arrays or processing only one string at a time, rather than combining them.