天生我材必有用,千金散尽还复来。 仰天大笑出门去,我辈岂是蓬蒿人。 大鹏一日同风起,扶摇直上九万里。 十步杀一人,千里不留行。 事了拂衣去,深藏身与名。 安能摧眉折腰事权贵,使我不得开心颜! 且乐生前一杯酒,何须身后千载名? 愿将腰下剑,直为斩楼兰。
 

JAVA中遍历String的不同方式之间的效率对比

最近在leetcode上用JAVA刷题,多次遇到遍历String的情况,常用的有两种,

一种是先转为char数组,在遍历;

一种是String自带的charAt方法。

根据c++的习惯,转为数组后操作比较顺手,而且代码简洁,但是又额外的空间浪费,于是好奇第一种方式的速度是否有提升,写了个简单的测试程序,结果挺意外的。。

        String s = "helloworld";
        StringBuilder sb = new StringBuilder();
        int c = 1000000;
        while(c>0){
            c--;
            sb.append(s);
        }
        String tests = sb.toString();
        char[] cs = tests.toCharArray();
        //看时间消耗
        //第一种遍历,使用char数组
        long s1 = System.currentTimeMillis();
        for(int i = 0;i < tests.length();i++){
            System.out.println(cs[i]);
        }
        long s2 = System.currentTimeMillis();

        //耗时
        //第二种遍历,使用charat
        long s3 = System.currentTimeMillis();
        for(int i = 0;i < tests.length();i++){
            System.out.println(tests.charAt(i));
        }
        long s4 = System.currentTimeMillis();
        System.out.println(s2-s1);
        System.out.println(s4-s3);
c 第一种 第二种

100

11 5

1000

55 42

10000

502 405

100000

4237 3859

1000000

39314 36691

 

也就是说,使用charAt的效率要高,而且不用额外的空间。

posted @ 2022-05-06 21:04  gudy  阅读(427)  评论(0编辑  收藏  举报