java lambda效率简单测试

2018-09-27  本文已影响0人  狂飙的蜗牛_013d

测试代码

    @Test
    public void test(){
        int initialCapacity = 10000000;
        List<Integer> originList = new ArrayList<>(initialCapacity);
        List<Integer> forList = new ArrayList<>(initialCapacity/2);
        List<Integer> lambdaList = new ArrayList<>(initialCapacity/2);

        for (int i = 0; i < initialCapacity; i++) {
            originList.add(i);
        }

        Long startTime = System.currentTimeMillis();

        for(Integer i : originList){
            if(i.intValue()%2==0){
                forList.add(i);
            }
        }
        Long endTime = System.currentTimeMillis();
        System.out.println("for 循环消耗时间="+(endTime-startTime));

        startTime = System.currentTimeMillis();
        lambdaList = originList.stream().filter(i->i.intValue()%2==0).collect(Collectors.toList());
        endTime = System.currentTimeMillis();
        System.out.println("lambda 循环消耗时间="+(endTime-startTime));
    }

测试结果

initialCapacity = 100000

for 循环消耗时间=3
lambda 循环消耗时间=90

initialCapacity = 1000000

for 循环消耗时间=12
lambda 循环消耗时间=127

initialCapacity = 10000000

for 循环消耗时间=45
lambda 循环消耗时间=281
上一篇下一篇

猜你喜欢

热点阅读