Recently wrote a dongdong, may consider the string splicing, think of several methods, but the performance is unknown, so with JUnit wrote a unit test.
The code is as follows:
- Import java.util.ArrayList;
- Import java.util.List;
- Import Org.apache.commons.lang.StringUtils;
- Import Org.junit.Test;
- Import Org.slf4j.Logger;
- Import Org.slf4j.LoggerFactory;
- public class TestString {
- Private final Logger Logger = Loggerfactory.getlogger (This.getclass ());
- @Test
- public void Testplus () {
- String s = "";
- Long ts = System.currenttimemillis ();
- for (int i = 0; i < 10000; i++) {
- s = s + string.valueof (i);
- }
- Long te = System.currenttimemillis ();
- Logger.info ("+ Cost {} MS", Te-ts);
- }
- @Test
- public void Testconcat () {
- String s = "";
- Long ts = System.currenttimemillis ();
- for (int i = 0; i < 10000; i++) {
- s = S.concat (string.valueof (i));
- }
- Long te = System.currenttimemillis ();
- Logger.info ("concat cost {} MS", Te-ts);
- }
- @Test
- public void Testjoin () {
- list<string> list = new arraylist<string> ();
- Long ts = System.currenttimemillis ();
- for (int i = 0; i < 10000; i++) {
- List.add (string.valueof (i));
- }
- Stringutils.join (List, "");
- Long te = System.currenttimemillis ();
- Logger.info ("Stringutils.join Cost {} MS", Te-ts);
- }
- @Test
- public void Teststringbuffer () {
- StringBuffer sb = new StringBuffer ();
- Long ts = System.currenttimemillis ();
- for (int i = 0; i < 10000; i++) {
- Sb.append (string.valueof (i));
- }
- Sb.tostring ();
- Long te = System.currenttimemillis ();
- Logger.info ("StringBuffer Cost {} MS", Te-ts);
- }
- @Test
- public void Teststringbuilder () {
- StringBuilder sb = new StringBuilder ();
- Long ts = System.currenttimemillis ();
- for (int i = 0; i < 100000; i++) {
- Sb.append (string.valueof (i));
- }
- Sb.tostring ();
- Long te = System.currenttimemillis ();
- Logger.info ("StringBuilder Cost {} MS", Te-ts);
- }
- }
The results of the operation are as follows:
11:00:22,359 INFO teststring:23-+ cost 1828 MS
11:00:22,921 INFO teststring:34-concat Cost 562 ms
11:00:22,937 INFO teststring:46-stringutils.join Cost ms
11:00:22,968 INFO teststring:58-stringbuffer Cost ms
11:00:23,031 INFO teststring:70-stringbuilder Cost + ms
Special attention is paid to the following:
The number of StringBuilder cycles is 10 times times that of the other, and if it is the same, then return 0, visible StringBuilder speed.
Summarize:
In the way of the worst efficiency, concat because it is the internal mechanism to achieve, more than the way of a lot better.
Join and StringBuffer, the difference is not small, join way faster, it can be seen in this JavaScript fast stitching string in the way in Java is also very suitable.
StringBuilder is the fastest, but its thread-safe problem, and only JDK5 support.
The "Go" Java 5 string concatenation method performance comparison.