您的位置:首页 > 编程语言 > Java开发

Java字符串连接操作的性能问题

2014-02-26 00:05 609 查看
首先,看一段实验程序:

package com.test;

class StringTest {

public static void main(String[] args) {

long start = 0;
long count = 100000;
String str = "test String contact..";
String result = "";
long s1 = System.currentTimeMillis();
while (start < count) {
result+=str;
start++;
}
long e1 = System.currentTimeMillis();
System.out.println("+ 连接执行时间:");
System.out.println(e1 - s1);

start = 0;
str = "test String contact..";
result="";
long s2 = System.currentTimeMillis();
while (start < count) {
result=result.concat(str);
start++;
}
long e2 = System.currentTimeMillis();

System.out.println("contact 连接执行时间:");
System.out.println(e2 - s2);

start = 0;
str = "test String contact..";
result="";
StringBuilder sb = new StringBuilder();
long s3 = System.currentTimeMillis();
while (start < count) {
sb.append(str);
start++;
}
long e3 = System.currentTimeMillis();

System.out.println("stringbuild 连接执行时间:");
System.out.println(e3 - s3);

start = 0;
str = "test String contact..";
result="";
StringBuffer sbu = new StringBuffer();
long s4 = System.currentTimeMillis();
while (start < count) {
sbu.append(str);
start++;
}
long e4 = System.currentTimeMillis();

System.out.println("stringbuffer 连接执行时间:");
System.out.println(e4 - s4);

}
}


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

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

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

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

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

public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}


StringBulid和StringBuffer的执行效率基本一致,综上分析,在大量的字符串拼接处理时,考虑到执行效率,应该使用StringBuild或StringBuffer,尤其是在高并发的场景下性能问题改善尤其明显。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: