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   coderwood  阅读(26172)  评论(2)    收藏  举报

努力加载评论中...

导航

< 2025年4月 >
30 31 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
点击右上角即可分享
微信分享提示