Java8 Lambda表达式与for性能测试

测试代码如下: 

package com.mew.kittyapi.test.lamda;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yanhu
 * @version 2019/4/9 下午 12:02
 */
public class LambdaMain {

    public static void main(String[] args) {

        int size = 1000000;
        long st;

        List<Integer> list = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            list.add(i);
        }

        st = System.currentTimeMillis();
        new ArrayList<String>(0).forEach(s -> {
        });
        System.out.println("lambda init: " + (System.currentTimeMillis() - st) + "ms");


        st = System.currentTimeMillis();
        Integer max1 = forMax(list);
        System.out.println("for: " + (System.currentTimeMillis() - st) + "ms, max: " + max1);


        st = System.currentTimeMillis();
        Integer max2 = foreachMax(list);
        System.out.println("foreach: " + (System.currentTimeMillis() - st) + "ms, max: " + max2);


        st = System.currentTimeMillis();
        Integer max3 = lambdaMax(list);
        System.out.println("lambda: " + (System.currentTimeMillis() - st) + "ms, max: " + max3);
    }

    /**
     * 使用正常for循环
     *
     * @param array
     * @return
     */
    private static Integer forMax(List<Integer> array) {
        Integer max = 0;
        int size = array.size();
        Integer it;
        for (int i = 0; i < size; i++) {
            it = array.get(i);
            if (it > max) {
                max = it;
            }
        }
        return max;
    }

    /**
     * 使用增强for循环
     *
     * @param array
     * @return
     */
    private static Integer foreachMax(List<Integer> array) {
        Integer max = 0;
        for (Integer it : array) {
            if (it > max) {
                max = it;
            }
        }
        return max;
    }

    static Integer max = 0;

    /**
     * 使用lambda表达式
     *
     * @param array
     * @return
     */
    private static Integer lambdaMax(List<Integer> array) {
        array.forEach(it -> {
            if (it > max) {
                max = it;
            }
        });
        return max;
    }
}

执行结果:

82f2c36acf0fb436fba7c3fe9aa2c7820c0.jpg

转载于:https://my.oschina.net/pipimao/blog/3034145

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值