for里面 i++; ++i; i-- ; --i 循环效率问题

论坛 期权论坛 脚本     
匿名技术用户   2021-1-5 08:51   59   0
今天String源码,看到了for循环的多种写法,闲来无事,测试一下for循环速度问题,下面是创建list对象,添加map,然后for循环list的所有集合,发现时间相差甚远,下面是最基础的代码,有大神解释一下,为什么吗?

public static void main(String[] args) {
    List list = new LinkedList();
    for (int i = 0; i < 1000000 ; i++) {
        Map map = new HashMap();
        list.add(map);
    }
        //开始for循环起始时间(纳秒)
        long start = System.nanoTime();
        /*
          下面是五中写法
          1.for (int i =0; i<list.size();i++) { }
          2. for (int i =0; i<list.size();++i) { } 
          3. for (int i = list.size(); i-- > 0;) { }
          4. for (int i = list.size(); i > 0;i--) { }
          5. for (int i = list.size(); --i >= 0;) { }
        */
        //for循环结束时间(纳秒)
        long end = System.nanoTime(); 
        //输出循环所需时间
        System.out.println(end - start);
}

时间输出,

第1种for循环平均2035444纳秒左右

第2种for循环平均1955434纳秒左右

第3种for循环平均1215002纳秒左右

第4种for循环平均1195011纳秒左右

第5种for循环平均10075023纳秒左右

总结,第五种方法 for (int i = list.size(); --i >= 0;) { } 循环最快

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP