最近写一个东东,可能会考虑到字符串拼接,想了几种方法,但对性能未知,于是用Junit写了个单元测试。
代码如下:
- 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);
- }
- }
运行结果如下:
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支持。