关于StringBuilder清空方式的比较

2021-12-30  本文已影响0人  沐小木沐

正好做个json字符串拼接的工具类,然后就突然想起了StringBuilder的数据清空问题。秉承着严谨的姿势(〃'▽'〃) ,那么做个测试类如下

public class Test {

    private static String a;
    private static long time;

    public static void main(String[] args) {
        long c = 100000000L;
        doWay1(c);
        doWay2(c);
        doWay3(c);
    }

    private static void doWay1(long count) {
        StringBuilder sb = new StringBuilder();
        time = System.currentTimeMillis();
        for (long i = 0; i < count; i++) {
            sb.delete(0, sb.length());
            sb.append("someThi1ng");
            sb.append("someThi2ng");
            sb.append("someThi3ng");
            sb.append("someThi4ng");
            sb.append("someThi5ng");
            sb.append("someThi6ng");
            a = sb.toString();
        }
        System.out.println("Way1=" + (System.currentTimeMillis() - time));
    }

    private static void doWay2(long count) {
        StringBuilder sb2 = new StringBuilder();
        time = System.currentTimeMillis();
        for (long i = 0; i < count; i++) {
            sb2.setLength(0);
            sb2.append("someThin1g");
            sb2.append("someThin2g");
            sb2.append("someThin3g");
            sb2.append("someThin4g");
            sb2.append("someThin5g");
            sb2.append("someThin6g");
            a = sb2.toString();
        }
        System.out.println("Way2=" + (System.currentTimeMillis() - time));
    }

    private static void doWay3(long count) {
        time = System.currentTimeMillis();
        StringBuilder sb3;
        for (long i = 0; i < count; i++) {
            sb3 = new StringBuilder();
            sb3.append("someThing1");
            sb3.append("someThing2");
            sb3.append("someThing3");
            sb3.append("someThing4");
            sb3.append("someThing5");
            sb3.append("someThing6");
            a = sb3.toString();
        }
        System.out.println("Way3=" + (System.currentTimeMillis() - time));
    }
}

考虑到函数执行顺序对程序的影响,按照多次排列规则变化函数顺序,那么得到以下数据(注:我是在64位window10机器上进行测试的,数据可能因为瞬时的CPU,磁盘占用,内存变化等因素影响,建议自己测试实验哈(=゚ω゚)ノ)

Way1=5633 Way2=5263  Way3=9774
Way1=5530 Way3=10824 Way2=5126
Way2=5034 Way1=4960  Way3=10353
Way2=5168 Way3=9965  Way1=5505
Way3=8350 Way1=5029  Way2=4958
Way3=7613 Way2=5164  Way1=4917

综合统计,way1 总共最小耗时2次 ,way2 总共最小耗时4次,way3 总共最小耗时0次,所以way2属于最优解,即 setLength(0); 最优解

上一篇下一篇

猜你喜欢

热点阅读