哪一种java循环方式性能最高

public class LoopTest {  
    private static List<Integer> list = new ArrayList<Integer>(1000000);  

    static {  
        for (int i = 0; i < 10000000; i++) {  
            list.add(i);  
        }  
    }  

    public void test(){  
        long startTime;  
        long endTime;  

        //style1
        startTime = System.nanoTime();  
        for (int i : list) { 
        }  
        endTime = System.nanoTime();  
        System.out.println("style1 —— for(int i : list) —— " + (endTime - startTime) + "毫微秒");  

        //style2  
        startTime = System.nanoTime();  
        for (int i = 0; i < list.size(); i++) {  
        }  
        endTime = System.nanoTime();  
        System.out.println("style2 —— for(int i = 0; i < list.size(); i++) —— " + (endTime - startTime) + "毫微秒");  

        //style3  
        startTime = System.nanoTime();  
        int size = list.size();
        for (int i = 0; i < size; i++) {  
        }  
        endTime = System.nanoTime();  
        System.out.println("style3 —— for(int i = 0; i < size; i++) —— " + (endTime - startTime) + "毫微秒");

        //style4
        startTime = System.nanoTime();
        for (int i = list.size() - 1; i > -1; i--) {
        }
        endTime = System.nanoTime();
        System.out.println("Style4 —— for(int i = list.size() - 1; i > -1; i--) —— " + (endTime - startTime) + "毫微秒");

    }  

    public static void main(String[] args) {  
        new LoopTest().test();  
    }  
} 

输出结果:
style1 —— for(int i : list) —— 39563185毫微秒
style2 —— for(int i = 0; i < list.size(); i++) —— 5012893毫微秒
style3 —— for(int i = 0; i < size; i++) —— 3683956毫微秒
Style4 —— for(int i = list.size() - 1; i > -1; i–)—— 3199474毫微秒

结论:
style1性能最低,原因增强的for循环内部使用了迭代iterator 形式,创建interator和调用interator.get() 都需要时间。
style2是程序员最常用的循环方式,性能一般,原因在于list.size()做为循环判断的标准,每次循环都要比较一次(没有意义)。
style3和style4性能差不多,单位是”毫微秒”,1秒=1000豪秒;1毫秒=1000微秒;1微秒=1000毫微秒。
style4性能最高,实践说明一切! 可有一个问题,经过多次测试发现style4不稳定,消耗时间偶尔会超过style3。

推荐:
style3和style4性能相差不多,style4不稳定,而且用style4有些时候会导致代码的可读性差。so,我推荐style3,JDK源码里也采用了style3。

int size = list.size();
for (int i = 0; i < size; i++) {  
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值