Java的StringBuilder三种清空方式性能对比

在Mybatis Generator的源码中看到了删除StringBuilder内容用的是setLength(0);想起来还有其他的方式可以删除,于是找了点文章,结果各种乱七八糟的东西让我很是烦躁,就手动撸了下试试。

环境为 JDK8u51, Intel Core i5-3230M, 8GB RAM, Win10 64bit

由于StringBuilder本身并没有提供clear或者empty之类的方法,所以常见的清空有三种方式:

  • new StringBuilder();
  • setLength(0);
  • delete(0, sb.length());

写的测试Demo如下:

package test;

public class TestStringBuilder {

    public static void main(String[] args) {
        wayNew();
        waySetLength();
        wayDelete();
    }
    
    private static void wayNew() {
        StringBuilder sb = new StringBuilder();
        long begin = System.currentTimeMillis();
        
        for (int i = 0; i < 100000000; i++) {
            sb = new StringBuilder("zxcvbnm");
            sb = new StringBuilder();
        }
        
        long end = System.currentTimeMillis();
        System.out.println("wayNew time costs:");
        System.out.println(end - begin);
    }
    
    private static void waySetLength() {
        StringBuilder sb = new StringBuilder();
        long begin = System.currentTimeMillis();
        
        for (int i = 0; i < 100000000; i++) {
            sb = new StringBuilder("asdfghj");
            sb.setLength(0);
        }
        
        long end = System.currentTimeMillis();
        System.out.println("waySetLength time costs:");
        System.out.println(end - begin);
    }
    
    private static void wayDelete() {
        StringBuilder sb = new StringBuilder();
        long begin = System.currentTimeMillis();
        
        for (int i = 0; i < 100000000; i++) {
            sb = new StringBuilder("qwertyu");
            sb.delete(0, sb.length());
        }
        
        long end = System.currentTimeMillis();
        System.out.println("wayDelete time costs:");
        System.out.println(end - begin);
    }
}

每次运行的结果都稍有不同,选取其中一次如下:

wayNew time costs:
1651
waySetLength time costs:
788
wayDelete time costs:
797

可以看到new的方式是开销最大的,其他两种在我测试时都不太稳定,有时候setLength快一点,有时候delete快一点,但是差距都不大。
结论:
就我个人感受来说:new >> delete ≈ setLength
我想我可能会用setLength多一点,因为参数给0就行,delete还要计算下length(),麻烦,哈哈。

标签: none

添加新评论

ali-01.gifali-58.gifali-09.gifali-23.gifali-04.gifali-46.gifali-57.gifali-22.gifali-38.gifali-13.gifali-10.gifali-34.gifali-06.gifali-37.gifali-42.gifali-35.gifali-12.gifali-30.gifali-16.gifali-54.gifali-55.gifali-59.gif

加载中……