首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

String性能比较解决方案

2013-08-01 
String性能比较public class Test {public static void main(String[] args) {final int SIZE 10000lon

String性能比较

public class Test {

public static void main(String[] args) {

final int SIZE = 10000;
long start = 0;

String str = new String();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE; i++)
str += "aba"+i;
System.out.println(System.currentTimeMillis() - start);


 String str2 = new String();
 start = System.currentTimeMillis();
 for (int i = 0; i < SIZE*100; i++)
 str2.concat("abc"+i);
 System.out.println(System.currentTimeMillis() - start);



StringBuffer sb = new StringBuffer();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
sb.append("abd"+i);
System.out.println(System.currentTimeMillis() - start);



StringBuilder sbu = new StringBuilder();
start = System.currentTimeMillis();
for (int i = 0; i < SIZE*100; i++)
sbu.append("abe"+i);
System.out.println(System.currentTimeMillis() - start);

}
}

输出:
813
218
250
172
几乎每次,concat的时间都比append少,这与理论不符啊?
[解决办法]
你把str2.concat改成 str2=str2.concat。因为你没有东西接住str2.concat的返回值,jvm就将其优化掉了

热点排行