Flask接口签名sign原理与实例代码浅析
262
2022-12-07
Java字符串拼接效率测试过程解析
测试代码:
public class StringJoinTest {
public static void main(String[] args) {
int count = 10000;
long begin, end, time;
begin = System.currentTimeMillis();
testString(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("拼接" + count + "次,String消耗时间:" + time + "毫秒");
begin = System.currentTimeMillis();
testStringBuffer(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("拼接" + count + "次,StringBuffer消耗时间:" + time + "毫秒");
begin = System.currentTimeMillis();
testStringBuilder(count);
end = System.currentTimeMillis();
time = end - begin;
System.out.println("拼接" + count + "次,StringBuilder消耗时间:" + time + "毫秒");
}
private static String testStringBuilder(int count) {
StringBuilder tem = new StringBuilder();
for (int i = 0; i < count; i++) {
tem.append("hello world!");
}
retRjoarrEnXturn tem.toString();
}
private static String testStringBuffer(int count) {
StringBuffer tem = new StringBuffer();
for (int i = 0; i < count; i++) {
tem.append("hello world!");
}
return tem.toString();
}
private static String testString(int count) {
String tem = "";
for (int i = 0; i < count; i++) {
tem += "hello world!";
}
return tem;
}
}
测试结果:
结论:
在少量字符串拼接时还看不出差别,但随着数量的增加,String+拼接效率显著降低。在达到100万次,我本机电脑已经无法执行String+拼接了,StringBuilder效率略高于StringBuffer。所以在开发过程中通常情况下推荐使用StringBuilder。
StringBuffer和StringBuildhttp://er的区别在于StringBuffer是线程安全的。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~