1. 程式人生 > 其它 >字串拼接方式效能對比

字串拼接方式效能對比

效能對比結果:StringBuilder>StringBuffer>StringUtils.join>concat>+

效能【指標:時間】對比程式碼:

public class Test {
  List<String> list = new ArrayList<>();
  @Before
  public void init(){
    IntStream.range(0, 100000).forEach((index) -> {
      list.add("str" + index);
    });
  }
  @org.junit.Test
  
public void test1() { String ss = ""; long startTime = System.currentTimeMillis(); for (String s : list) { ss += s; } System.out.println(System.currentTimeMillis() - startTime); } @org.junit.Test public void test2() { String ss = ""; long startTime = System.currentTimeMillis();
for (String s : list) { ss=ss.concat(s); } System.out.println(System.currentTimeMillis() - startTime); } @org.junit.Test public void test3() { StringBuilder ss = new StringBuilder(); long startTime = System.currentTimeMillis(); for (String s : list) { ss.append(s); } System.out.println(System.currentTimeMillis()
- startTime); } @org.junit.Test public void test4() { long startTime = System.currentTimeMillis(); StringUtils.join(list); System.out.println(System.currentTimeMillis() - startTime); } @org.junit.Test public void test5() { StringBuffer ss = new StringBuffer(); long startTime = System.currentTimeMillis(); for (String s : list) { ss.append(s); } System.out.println(System.currentTimeMillis() - startTime); } }

耗時結果:

第一種:33809

第二種:8851

第三種:6

第四種:12

第五種:7