测试 StringBuffer

本文详细介绍了Java中String Buffer和StringBuilder的使用方法、性能对比及应用场景,深入理解其内部实现原理。
public class TestStringBuffer {

    /**
     * @param args
     */
    public static void main(String[] args) {
        TestStringBuffer t = new TestStringBuffer();
        System.out.println();
        t.test0();
        // t.test1(); // 4203
        // t.test2(); // 0
        // t.test3(); // 4234
    }

    void test0() {
        String s1 = "xy123";
        s1 = "abcdef";
        s1 = new String("ABCDEFG");
        s1.replace('D', 'y');
        System.out.println(s1); // ABCDEFG 没变

        StringBuffer s2 = new StringBuffer("x");
        System.out.println(s2);
        s2.append(s1); // xabcdef
        s2.replace(2, 4, "_");
        System.out.println(s2);
        s2 = new StringBuffer(s1); // abcdef
        System.out.println(s2);

        String s3 = s1.substring(1, 3);// 截取index从第1个到第3个前面的 abcdef ==> bc
        System.out.println(s3); // bc

        StringBuilder s4 = new StringBuilder("ABCDEFGH-");
        s4.append(true);
        System.out.println(s4);        // ABCDEFGH-true
    }

    void test1() {
        String tempstr = "abcdefghijklmnopqrstuvwxyz";
        int times = 5000;
        long lstart1 = System.currentTimeMillis();
        String str = "";
        for (int i = 0; i < times; i++) {
            str += tempstr;
        }
        long lend1 = System.currentTimeMillis();
        long time = (lend1 - lstart1);
        System.out.println(time);

    }

    void test2() {
        String tempstr = "abcdefghijklmnopqrstuvwxyz";
        int times = 5000;
        long lstart2 = System.currentTimeMillis();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < times; i++) {
            sb.append(tempstr);
        }
        long lend2 = System.currentTimeMillis();
        long time2 = (lend2 - lstart2);
        System.out.println(time2);

    }

    void test3() {
        String tempstr = "abcdefghijklmnopqrstuvwxyz";
        int times = 5000;
        long lstart2 = System.currentTimeMillis();
        String str = "";
        for (int i = 0; i < times; i++) {
            StringBuffer sb = new StringBuffer(str);
            sb.append(tempstr);
            str = sb.toString();
        }
        long lend2 = System.currentTimeMillis();
        long time2 = (lend2 - lstart2);
        System.out.println(time2);

    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值