测试代码:

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!");
}
return 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和StringBuilder的区别在于StringBuffer是线程安全的。

最新文章

  1. mysql数据库封装
  2. 在Excel中制作复合饼图
  3. maven下载速度慢的解决方法(转)
  4. Install Shield 打包教程
  5. “粪便银行”:救人拿钱两不误 A Poop Bank in Massachusetts Will Pay You $40 Every Day
  6. idl 批量裁剪代码
  7. [Ember] Creating Your First Ember.js Project with Ember-CLI
  8. SpringSource Tools Suite 字体偏小问题
  9. freemarker 遍历 hashmap 到select option
  10. 五种开源协议(GPL,LGPL,BSD,MIT,Apache)介绍
  11. layui 重加载
  12. hive 一次更新多个分区的数据
  13. OJ:一道考察多态的题目
  14. 虚拟机下 centos7 无法连接网络
  15. MACE(2)-----模型编译
  16. [GDOI2018]滑稽子图
  17. html5-css的引入
  18. Redis客户端连接
  19. struts2框架之OGNL表达式概述(在代码中使用OGNL表达式)
  20. 属性attribute和property的区别

热门文章

  1. hdu 1392 Surround the Trees 凸包裸题
  2. python+win32+ie浏览器操作 TypeError: getElementById() takes exactly 1 argument (2 given)
  3. javaSE习题 第二章 基本数据类型和数组
  4. 力扣(LeetCode) 66. 加一
  5. (6)进程---Event事件
  6. Getting started with Processing 第九章总结
  7. java --&gt; Long和long/Integer和int
  8. 自定义广播(BroadcastReceiver)事件 --Android开发
  9. 通过ambari安装hadoop集群,ZT
  10. SPL之Iterator和ArrayAccess的结合使用