Lambda表达式速度较慢? [英] Lambda expressions slower?

查看:222
本文介绍了Lambda表达式速度较慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有这段代码:

 PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(dscsortedMAP.size(), new Comparator<Map.Entry<Integer, Integer>>() {

        @Override
        public int compare(Map.Entry<Integer, Integer> arg0, Map.Entry<Integer, Integer> arg1) {

            return arg1.getValue().compareTo(arg0.getValue());
        }
    });

比IntelliJ IDEA友好的建议,我可以将上面的代码替换为如下所示的lambda表达式:

    PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(dscsortedMAP.size(), (arg0, arg1) -> {

        return arg1.getValue().compareTo(arg0.getValue());
    });

你猜怎么了,在我的方法中,2.代码的执行时间慢了20倍?!第一个版本花了 7毫秒对列表进行排序,而在lambda表达之后,是 140毫秒?!

我在这里错过了什么吗?我没有测试执行时间是否随数据增长按比例增加.也许那只是最初的一次CPU时间?

解决方案

首次使用lambda时,JVM必须生成并加载该类的字节码.首次使用任何lambda时,都会加载大多数lambda代码生成库.

我发现使用Lambda比较器会比较慢.在将来的版本中,情况可能并非如此.更重要的是,lambda代码肯定需要加载并预热才能更快.

您的代码运行时间不足以说明.在进行任何测量之前,我将代码预热至少2-10秒.

当您使用比较器对大型列表进行排序时,可以称为N log2 N倍,这很多.效率低下的情况都会显示为明显.

I had this piece of code below:

 PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(dscsortedMAP.size(), new Comparator<Map.Entry<Integer, Integer>>() {

        @Override
        public int compare(Map.Entry<Integer, Integer> arg0, Map.Entry<Integer, Integer> arg1) {

            return arg1.getValue().compareTo(arg0.getValue());
        }
    });

Than IntelliJ IDEA friendly suggested that I can replace the code above to a lambda expression like below:

    PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(dscsortedMAP.size(), (arg0, arg1) -> {

        return arg1.getValue().compareTo(arg0.getValue());
    });

Well guess what happened, in my method the execution time of the 2. code executed 20 times slower?! First version took 7 miliseconds to sort the list, and after lambda expression it was 140 miliseconds?!

Am I missing something here? I didn't test if the execuation time proportionally increases as data grows. maybe thats just the initial one time cpu time?

解决方案

The first time a lambda is used, the JVM has to generate the byte code of the class and load it. The first time any lambda is used, most of the lambda code generating library is loaded.

I have found that using a Lambda Comparator can be slower. It is likely that in future version this will not be the case. More importantly, lambda code definitely needs to be loaded and warmed up to be fast.

Your code isn't run long enough to say. I would warm the code up for at least 2 - 10 seconds before taking any measurement.

When you use a Comparator to sort a large list it can be called N log2 N times which is a lot. Any inefficiency with show up as significant.

这篇关于Lambda表达式速度较慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆