java中字符串拼接 String 和 StringBuilder(StringBuffer)的使用

字符串拼接是个常用的功能,经常性使用String做字符串拼接,当拼接次数多的时候,使用String方法会消耗大量的性能和时间,因为每次String拼接时都会建立一个新的对象,随着拼接次数的增多,性能消耗、时间消耗会大量增加,这个时候应该使用StringBuilder方法。

复制代码
 1 public static void main(String[] args) {
 2         try {
 3             int count = 500;
 4 
 5             long begin = System.currentTimeMillis();
 6             testString(count);
 7             long end = System.currentTimeMillis();
 8             long time = end - begin;
 9             System.out.println("String 方法拼接"+count+"次消耗时间:" + time + "毫秒");
10 
11             begin = System.currentTimeMillis();
12             testStringBuilder(count);
13             end = System.currentTimeMillis();
14             time = end - begin;
15             System.out.println("StringBuilder 方法拼接"+count+"次消耗时间:" + time + "毫秒");
16 
17         } catch (Exception e) {
18             e.printStackTrace();
19         }
20 
21     }
22 
23     private static String testString(int count) {
24         String result = "";
25 
26         for (int i = 0; i < count; i++) {
27             result += "hello ";
28         }
29 
30         return result;
31     }
32 
33     private static String testStringBuilder(int count) {
34         StringBuilder sb = new StringBuilder();
35 
36         for (int i = 0; i < count; i++) {
37             sb.append("hello");
38         }
39 
40         return sb.toString();
41     }
复制代码

 

运行结果:

String 方法拼接500次消耗时间:2毫秒
StringBuilder 方法拼接500次消耗时间:0毫秒
String 方法拼接50000次消耗时间:4973毫秒
StringBuilder 方法拼接50000次消耗时间:3毫秒

 

posted on 2015-01-05 10:55  coderwood  阅读(26193)  评论(2)    收藏  举报

编辑推荐:
· 协程本质是函数加状态机——零基础深入浅出 C++20 协程
· 编码之道,道心破碎。
· 记一次 .NET 某发证机系统 崩溃分析
· 微服务架构学习与思考:SOA架构与微服务架构对比分析
· tomcat为什么假死了
阅读排行:
· 知名开源项目Alist被收购!惹程序员众怒,开团炮轰甲方
· 突发,小红书开发者后门被破解?!
· 历时半年,我将一个大型asp.net的零代码快速开发平台转成了java
· [原创]《C#高级GDI+实战:从零开发一个流程图》第03章:画一个线,连接两个矩形!
· C# 将 CSV 转化为 Excel

导航

< 2025年6月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 1 2 3 4 5
6 7 8 9 10 11 12
点击右上角即可分享
微信分享提示