字符串拼接的几种方式--性能问题

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 import org.apache.commons.lang.StringUtils;
 4 import org.junit.Test;
 5 import org.slf4j.Logger;
 6 import org.slf4j.LoggerFactory;
 7 public class TestString {
 8     private final Logger logger = LoggerFactory.getLogger(this.getClass());
 9     @Test
10     public void testPlus() {
11         String s = "";
12         long ts = System.currentTimeMillis();
13         for (int i = 0; i < 10000; i++) {
14             s = s + String.valueOf(i);
15         }
16         long te = System.currentTimeMillis();
17         logger.info("+ cost {} ms", te - ts);
18     }
19     @Test
20     public void testConcat() {
21         String s = "";
22         long ts = System.currentTimeMillis();
23         for (int i = 0; i < 10000; i++) {
24             s = s.concat(String.valueOf(i));
25         }
26         long te = System.currentTimeMillis();
27         logger.info("concat cost {} ms", te - ts);
28     }
29     @Test
30     public void testJoin() {
31         List<String> list = new ArrayList<String>();
32         long ts = System.currentTimeMillis();
33         for (int i = 0; i < 10000; i++) {
34             list.add(String.valueOf(i));
35         }
36         StringUtils.join(list, "");
37         long te = System.currentTimeMillis();
38         logger.info("StringUtils.join cost {} ms", te - ts);
39     }
40     @Test
41     public void testStringBuffer() {
42         StringBuffer sb = new StringBuffer();
43         long ts = System.currentTimeMillis();
44         for (int i = 0; i < 10000; i++) {
45             sb.append(String.valueOf(i));
46         }
47         sb.toString();
48         long te = System.currentTimeMillis();
49         logger.info("StringBuffer cost {} ms", te - ts);
50     }
51     @Test
52     public void testStringBuilder() {
53         StringBuilder sb = new StringBuilder();
54         long ts = System.currentTimeMillis();
55         for (int i = 0; i < 100000; i++) {
56             sb.append(String.valueOf(i));
57         }
58         sb.toString();
59         long te = System.currentTimeMillis();
60         logger.info("StringBuilder cost {} ms", te - ts);
61     }
62 }

运行结果如下:
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 16 ms
11:00:22,968 INFO TestString:58 - StringBuffer cost 31 ms
11:00:23,031 INFO TestString:70 - StringBuilder cost 63 ms


要特别注意的是:
StringBuilder 循环的次数是其它的10倍,如果是一样,那么返回 0,可见StringBuilder 的速度之快。

总结:
用+的方式效率最差,concat由于是内部机制实现,比+的方式好了不少。
Join 和 StringBuffer,相差不大,Join方式要快些,可见这种JavaScript中快速拼接字符串的方式在Java中也非常适用。
StringBuilder 的速度最快,但其有线程安全的问题,而且只有JDK5支持。

posted @ 2016-05-12 09:24  习惯沉淀  阅读(698)  评论(0编辑  收藏  举报