Java中for循环效率比较

先说结论:

对于遍历一个1千万条数据的arrayList,fori循环最快,iterator其次,foreach再其次,forStream最慢。

在这里插入图片描述

测试代码

public class ForSpeedTest {

//    private static final long FOR_COUNT = 10000_0000;
    private static final long FOR_COUNT = 1000_0000;
//    private static final long FOR_COUNT = 100_0000;
//    private static final long FOR_COUNT = 10_0000;
//    private static final long FOR_COUNT = 1_0000;
//    private static final long FOR_COUNT = 100;

    private static List<String> arrayList = new ArrayList<>();

    static {
    	//数据准备
        for (int i = 0; i < FOR_COUNT; i++) {
            arrayList.add("abc" + i);
        }  
    }

    public static void main(String[] args) throws Exception{
        Thread.sleep(1000);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("forI");
        forI();
        stopWatch.stop();
        stopWatch.start("forEach");
        forEeach();
        stopWatch.stop();
        stopWatch.start("forStream");
        forStream();
        stopWatch.stop();
        stopWatch.start("forI2");
        forI2();
        stopWatch.stop();
        stopWatch.start("iterator");
        forIterator();
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

    private static void forI() {
        long size = arrayList.size();
        for (int i = 0; i < size; i++) {

        }
    }

    private static void forEeach() {
        for (String s : arrayList) {

        }
    }

    private static void forStream() {
        arrayList.forEach(x -> {

        });
    }


    private static void forI2() {
        for (int i = 0; i < arrayList.size(); i++) {

        }
    }

    private static void forIterator() {
        Iterator<String> iterator = arrayList.iterator();
        while(iterator.hasNext()){
            iterator.next();
        }
    }

}
  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值