java stringbuilder 3种清空方法性能比较

java stringbuilder 清空问题

我也是碰到了这个问题才开始研究的,网上答案偏多,并且时间范围也比较大,各个版本的java 优化也不清楚,只能说我的java环境是1.7,测试给大家看。

三种思想

1、新生成一个,旧的由系统自动回收 
2、delete 方法 
builder1.delete(0, builder.length()); 
3、Length 
StringBuilder val = new StringBuilder(); 
val.Append(“….”); 
val.Length = 0;//清空

代码

        StringBuilder builder = new StringBuilder();  
        long time = System.currentTimeMillis();  
        for(int i=0;i<10000000;i++){  
            builder = new StringBuilder();  
            builder.append("aa");  
            builder.append("bb");  
            builder.append("cc");  
            builder.append("dd");  
            builder.append("ee");  
        }  
        System.out.println("new 耗时:" + (System.currentTimeMillis() - time));  
        long time1 = System.currentTimeMillis(); 
        StringBuilder builder1 = new StringBuilder();
        for(int i=0;i<10000000;i++){  
            builder1.delete(0, builder.length());  
            builder1.append("a");  
            builder1.append("b");  
            builder1.append("c");  
            builder1.append("d");  
            builder1.append("e");  
        }  
        System.out.println("delete 耗时:" + (System.currentTimeMillis() - time1));  
        long time2 = System.currentTimeMillis(); 
        StringBuilder builder2 = new StringBuilder();
        for(int i=0;i<10000000;i++){  
            builder2.setLength(0);  
            builder2.append("1a");  
            builder2.append("1b");  
            builder2.append("1c");  
            builder2.append("1d");  
            builder2.append("1e");  
        }  
        System.out.println("setLenth=0 耗时:" + (System.currentTimeMillis() - time2));  

结果一:

new 耗时:485 
delete 耗时:471 
setLenth=0 耗时:385

结果二:

new 耗时:621 
delete 耗时:411 
setLenth=0 耗时:423

总结

方法二和方法三耗时是差不多的,每次运行花费的时间是不一样的,目前没有去计算每一种方法所占用的资源分别是多少

你可能感兴趣的:(java)