string,stringbubuilder,stringbuffer 添加字符串的时间比较

    public static void main(String[] args) {
        teststring();
        teststringbuilder();
        teststringbuffer();
    }

    public static void teststring() {
        long begintime = System.currentTimeMillis();
        String str="";
        for (int i = 0; i < 100000; i++) {
            str+=i;
        }
        long endtime = System.currentTimeMillis();
        System.out.println(endtime - begintime);
    }

    public static void teststringbuilder() {
        long begintime = System.currentTimeMillis();
        StringBuilder sBuilder=new StringBuilder("");
        for (int i = 0; i < 100000; i++) {
            sBuilder.append(i);
        }
        long endtime = System.currentTimeMillis();
        System.out.println(endtime - begintime);
    }

    public static void teststringbuffer() {
        long begintime = System.currentTimeMillis();
        StringBuffer sf=new StringBuffer("");
        for (int i = 0; i < 100000; i++) {
            sf.append(i);
        }
        long endtime = System.currentTimeMillis();
        System.out.println(endtime - begintime);
    }

耗时

11292
3
3

你可能感兴趣的:(JAVA笔记,JAVA代码记录)