Use
Concatenation operator (+)
String Concat method-Concat (string Str)
Stringbuffer append method-append (string Str)
Stringbuilder append method-append (string Str)
Perform performance tests.
Environment: win7 32-bit, CPU dual-core 2.5 GHz, 2 GB memory.
The test code is as follows:
Private final static int OUTER_ITERATION = 10; <br/> private final static int INNER_ITERATION = 50000; </p> <p>/** <br/> * @ param args <br/> */<br/> public static void main (String [] args) {<br/> String addTestStr = ""; <br/> String concatTestStr = ""; <br/> StringBuffer concatTestSb = null; <br/> StringBuilder concatTestSbu = null; </p> <p> for (int outerIndex = 0; outerIndex <OUTER_ITERATION; outerIndex ++) {<br/> StopWatch stopWatch = new LoggingStopWatch ("StringAddConcat "); <br/> addTestStr = ""; <br/> for (int innerIndex = 0; innerIndex <INNER_ITERATION; innerIndex ++) <br/> addTestStr + = "*"; <br/> stopWatch. stop (); <br/>}</p> <p> for (int outerIndex = 0; outerIndex <OUTER_ITERATION; outerIndex ++) {<br/> StopWatch stopWatch = new LoggingStopWatch ("StringConcat"); <br/> concatTestStr = ""; <br/> for (int innerIndex = 0; innerIndex <INNER_ITERATION; innerIndex ++) <br/> concatTestStr. concat ("*"); <br/> stopWatch. stop (); <br/>}</p> <p> for (int outerIndex = 0; outerIndex <OUTER_ITERATION; outerIndex ++) {<br/> StopWatch stopWatch = new LoggingStopWatch ("StringBufferConcat"); <br/> concatTestSb = new StringBuffer (); <br/> for (int innerIndex = 0; innerIndex <INNER_ITERATION; innerIndex ++) <br/> concatTestSb. append ("*"); <br/> stopWatch. stop (); <br/>}</p> <p> for (int outerIndex = 0; outerIndex <OUTER_ITERATION; outerIndex ++) {<br/> StopWatch stopWatch = new LoggingStopWatch ("StringBuilderConcat"); <br/> concatTestSbu = new StringBuilder (); <br/> for (int innerIndex = 0; innerIndex <INNER_ITERATION; innerIndex ++) <br/> concatTestSbu. append ("*"); <br/> stopWatch. stop (); <br/>}</p> <p>}
Test results:
Performance Statistics 06:16:00-06:16:30
Tag |
MS (avg) |
Min |
Max |
Std Dev |
Count |
Stringaddconcat |
9355.4 |
7860 |
10046 |
547.7 |
10 |
Stringbufferconcat |
3.5 |
0 |
5 |
2.3 |
10 |
Stringbuilderconcat |
2.0 |
0 |
5 |
2.4 |
10 |
Stringconcat |
3.1 |
0 |
6 |
2.5 |
10 |