首页 > 技术文章 > Java字符串连接操作的性能问题

xiayangy 2014-02-26 00:05 原文

首先,看一段实验程序:

 1 package com.test;
 2 
 3 class StringTest {
 4 
 5     public static void main(String[] args) {
 6         
 7         long start = 0;
 8         long count = 100000;
 9         String str = "test String contact..";
10         String result = "";
11         long s1 = System.currentTimeMillis();
12         while (start < count) {
13             result+=str;
14             start++;
15         }
16         long e1 = System.currentTimeMillis();
17         System.out.println("+ 连接执行时间:");
18         System.out.println(e1 - s1);
19         
20         start = 0;
21         str = "test String contact..";
22         result="";
23         long s2 = System.currentTimeMillis();
24         while (start < count) {
25             result=result.concat(str);
26             start++;
27         }
28         long e2 = System.currentTimeMillis();
29         
30         System.out.println("contact 连接执行时间:");
31         System.out.println(e2 - s2);
32         
33         start = 0;
34         str = "test String contact..";
35         result="";
36         StringBuilder sb = new StringBuilder();
37         long s3 = System.currentTimeMillis();
38         while (start < count) {
39             sb.append(str);
40             start++;
41         }
42         long e3 = System.currentTimeMillis();
43         
44         System.out.println("stringbuild 连接执行时间:");
45         System.out.println(e3 - s3);
46         
47         start = 0;
48         str = "test String contact..";
49         result="";
50         StringBuffer sbu = new StringBuffer();
51         long s4 = System.currentTimeMillis();
52         while (start < count) {
53             sbu.append(str);
54             start++;
55         }
56         long e4 = System.currentTimeMillis();
57         
58         System.out.println("stringbuffer 连接执行时间:");
59         System.out.println(e4 - s4);
60         
61         
62     }
63 }

 

上述测试程序的执行结果:

+ 连接执行时间:
156960
contact 连接执行时间:
40896
stringbuild 连接执行时间:
8
stringbuffer 连接执行时间:
7

从结果来看StringBuild连接字符串的效率最高,直接使用加号连接字符串的效率最低。

分析一下上述效率差别之大的原因:
"+"进行字符串连接实际上是在循环内部每次新建StringBuild对象进行字符串的拼接,这样会占用大量内存,jvm内存回收时间不定,导致其执行效率很低;

contact执行过程中也新建了许多内存对象,这是其执行效率低下的主要原因:

 1  public String concat(String str) {
 2         int otherLen = str.length();
 3         if (otherLen == 0) {
 4             return this;
 5         }
 6         int len = value.length;
 7         char buf[] = Arrays.copyOf(value, len + otherLen);
 8         str.getChars(buf, len);
 9         return new String(buf, true);
10     }

StringBulid和StringBuffer的执行效率基本一致,综上分析,在大量的字符串拼接处理时,考虑到执行效率,应该使用StringBuild或StringBuffer,尤其是在高并发的场景下性能问题改善尤其明显。

 

 

 

 

推荐阅读