美文网首页
java字符串相加速度最慢,转换为char数组相加次之,stri

java字符串相加速度最慢,转换为char数组相加次之,stri

作者: ElonYanJ | 来源:发表于2018-03-12 15:53 被阅读11次

        long start1 = System.currentTimeMillis();
        String a = "";
        for (int i = 0; i < 1000; i++) {
            a = a + "a";
        }
        long end = System.currentTimeMillis() - start1;
        Log.d("dddeferefr", end + "");

        long start2 = System.currentTimeMillis();
        StringBuilder as = new StringBuilder();
        for (int i = 0; i < 10000; i++) {
            as.append("a");
        }
        long end2 = System.currentTimeMillis() - start2;
        Log.d("dddeferefr", end2 + "");


        long start3 = System.currentTimeMillis();
        char[] ss = new char[0];
        for (int i = 0; i < 10000; i++) {
            int length = ss.length;
            char[] next = new char[length + 1];
            System.arraycopy(ss, 0, next, 0, length);
            next[length] = 'a';
            ss = next;
        }
        String s = new String(ss);
        long end3 = System.currentTimeMillis() - start3;
        Log.d("dddeferefr", end3 + "");

结果
12
3
143


        long start1 = System.currentTimeMillis();
        String a = "";
        for (int i = 0; i < 1000; i++) {
            a = a + 'a';
        }
        long end = System.currentTimeMillis() - start1;
        Log.d("dddeferefr", end + "");

        long aaa = System.currentTimeMillis();
        StringBuilder as = new StringBuilder();
        for (int i = 0; i < 10000; i++) {
            as.append('a');
        }
        String ssss = as.toString();
        long bbb = System.currentTimeMillis() - aaa;
        Log.d("dddeferefr", bbb + "||" + ssss);

        long cccc = System.currentTimeMillis();
        char[] ss = new char[0];
        for (int i = 0; i < 10000; i++) {
            int length = ss.length;
            char[] next = new char[length + 1];
            System.arraycopy(ss, 0, next, 0, length);
            next[length] = 'a';
            ss = next;
        }
        String s = new String(ss);
        long dddd = System.currentTimeMillis() - cccc;
        Log.d("dddeferefr", dddd + "||" + s);


        long start4 = System.currentTimeMillis();
        for (int i = 0; i < 9999; i++) {
            as.deleteCharAt(0);
        }
        String dfsd = as.toString();
        long end4 = System.currentTimeMillis() - start4;
        Log.d("dddeferefr", end4 + "||" + dfsd);


        long start5 = System.currentTimeMillis();
        for (int i = 0; i < 9999; i++) {
            int lengthSubstract = ss.length;
            char[] nextRest = new char[lengthSubstract - 1];
            System.arraycopy(ss, 1, nextRest, 0, lengthSubstract - 1);
            ss = nextRest;
        }
        String send = new String(ss);
        long end5 = System.currentTimeMillis() - start5;
        Log.d("dddeferefr", end5 + "||" + send);

相关文章

网友评论

      本文标题:java字符串相加速度最慢,转换为char数组相加次之,stri

      本文链接:https://www.haomeiwen.com/subject/gngnfftx.html