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

今天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;) { }   循环最快

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值