package test;
import org.apache.commons.lang.StringUtils;
public class CutString {
//性能最差
public String testPlus() {
String s = "";
for (int i = 0; i < 10000; i++) {
s = s + String.valueOf(i);
}
return s;
}
//较好
public String testConcat() {
String s = "";
for (int i = 0; i < 10000; i++) {
s = s.concat(String.valueOf(i));
}
return s;
}
//性能与testStringBuffer相差无几,比其要好
public String testJoin() {
String[] list = new String[10000];
for (int i = 0; i < 10000; i++) {
list[i] = String.valueOf(i);
}
return StringUtils.join(list, "");
}
public String testStringBuffer() {
StringBuffer sb = new StringBuffer();
long l1 = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
sb.append(String.valueOf(i));
}
long l2 = System.currentTimeMillis();
System.out.println(l2-l1);
return sb.toString();
}
//性能最高的方法
public void testStringBuilder() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append(String.valueOf(i));
}
sb.toString();
}
public static void main(String[] args) {
System.out.println(new CutString().testStringBuffer());
}
}
运行结果如下:
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
阅读(1533) | 评论(0) | 转发(0) |