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毫秒

 

转载于:https://www.cnblogs.com/coderwood/p/4203030.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值