[java,2017-05-16] java中清空StringBuffer的方法以及耗费时间比较

java中清空StringBuffer的方法,我能想到的有4种:

1. buffer.setLength(0);  设置长度为0

2. buffer.delete(0, buffer.length());  删除0到末尾

3. buffer.replace(0, buffer.length(), "");  替换所有内容为空字符串

4. buffer=new StringBuffer();   创建新的StringBuffer

那么这4种方法哪种消耗的时间最少呢?

我对上面4种方法分别进行了百万次的循环,代码如下:

 1 public class StringBufferTest {
 2     public static void main(String[] args) {
 3         StringBuffer buffer=new StringBuffer();
 4         Long time1=System.currentTimeMillis();
 5         for(int i=1;i<1000000;i++){
 6             buffer.append("hello,world"+i);
 7             buffer.setLength(0);
 8         }
 9         Long time2=System.currentTimeMillis();
10         System.out.println("setLength cost==="+(time2-time1));
11         
12         Long time3=System.currentTimeMillis();
13         for(int i=1;i<1000000;i++){
14             buffer.append("hello,world"+i);
15             buffer.delete(0, buffer.length());
16         }
17         Long time4=System.currentTimeMillis();
18         System.out.println("delete cost==="+(time4-time3));
19         
20         Long time5=System.currentTimeMillis();
21         for(int i=1;i<1000000;i++){
22             buffer.append("hello,world"+i);
23             buffer.replace(0, buffer.length(), "");
24         }
25         Long time6=System.currentTimeMillis();
26         System.out.println("replace cost==="+(time6-time5));
27         
28         Long time7=System.currentTimeMillis();
29         for(int i=1;i<1000000;i++){
30             buffer.append("hello,world"+i);
31             buffer=new StringBuffer();
32         }
33         Long time8=System.currentTimeMillis();
34         System.out.println("new cost==="+(time8-time7));
35     }
36 }

得到了如下结果,为了排除偶然性,进行了5次测试:

    

           

通过上面的结果我们可以看出:

最耗费时间的是创建对象的方法(new StringBuffer()),其次是设置长度的方法(setLength(0));

最节省时间的是删除的方法(delete(0, buffer.length())),其次是替换的方法(replace(0, buffer.length(), ""))。

原文地址:https://www.cnblogs.com/shijt/p/9046796.html