Java lambdas比匿名类慢20倍 [英] Java lambdas 20 times slower than anonymous classes

查看:83
本文介绍了Java lambdas比匿名类慢20倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到了很多关于Java lambdas性能的问题,但是大多数问题都像Lambdas稍快一点,但在使用闭包时变慢或预热与执行时间不同或其他类似事情。

I've seen a lot of questions here about Java lambdas performance, but most of them go like "Lambdas are slightly faster, but become slower when using closures" or "Warm-up vs execution times are different" or other such things.

然而,我在这里遇到了一件相当奇怪的事情。考虑此LeetCode问题

However, I hit a rather strange thing here. Consider this LeetCode problem:


给定一组非重叠间隔,在
区间插入一个新区间(必要时合并)。

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

你可以假设间隔最初是根据
的开始时间排序的。

You may assume that the intervals were initially sorted according to their start times.

问题标记很难,所以我认为线性方法并不是他们想要的。所以我决定想出一种聪明的方法,将二进制搜索与对输入列表的修改结合起来。现在问题在修改输入列表时并不是很清楚 - 它表示插入,即使签名需要返回对列表的引用,但现在也不用担心。这是完整的代码,但只有前几行与此问题相关。我在这里保留其余部分,以便任何人都可以尝试:

The problem was tagged hard, so I assumed that a linear approach is not what they want there. So I decided to come up with a clever way to combine binary search with modifications to the input list. Now the problem is not very clear on modifying the input list—it says "insert", even though the signature requires to return a reference to list, but never mind that for now. Here's the full code, but only the first few lines are relevant to this question. I'm keeping the rest here just so that anyone can try it:

public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
    int start = Collections.binarySearch(intervals, newInterval,
                                         (i1, i2) -> Integer.compare(i1.start, i2.start));
    int skip = start >= 0 ? start : -start - 1;
    int end = Collections.binarySearch(intervals.subList(skip, intervals.size()),
                                       new Interval(newInterval.end, 0),
                                       (i1, i2) -> Integer.compare(i1.start, i2.start));
    if (end >= 0) {
        end += skip; // back to original indexes
    } else {
        end -= skip; // ditto
    }
    int newStart = newInterval.start;
    int headEnd;
    if (-start - 2 >= 0) {
        Interval prev = intervals.get(-start - 2);
        if (prev.end < newInterval.start) {
            // the new interval doesn't overlap the one before the insertion point
            headEnd = -start - 1;
        } else {
            newStart = prev.start;
            headEnd = -start - 2;
        }
    } else if (start >= 0) {
        // merge the first interval
        headEnd = start;
    } else { // start == -1, insertion point = 0
        headEnd = 0;
    }
    int newEnd = newInterval.end;
    int tailStart;
    if (-end - 2 >= 0) {
        // merge the end with the previous interval
        newEnd = Math.max(newEnd, intervals.get(-end - 2).end);
        tailStart = -end - 1;
    } else if (end >= 0) {
        newEnd = intervals.get(end).end;
        tailStart = end + 1;
    } else { // end == -1, insertion point = 0
        tailStart = 0;
    }
    intervals.subList(headEnd, tailStart).clear();
    intervals.add(headEnd, new Interval(newStart, newEnd));
    return intervals;
}

这个工作正常并且已被接受,但运行时间为80毫秒,而大多数解决方案是4-5毫秒,大约18-19毫秒。当我查看它们时,它们都是线性的,非常原始的。不是人们会对标记为硬的问题所期望的。

This worked fine and got accepted, but with 80 ms runtime, while most solutions were 4-5 ms and some 18-19 ms. When I looked them up, they were all linear and very primitive. Not something one would expect from a problem tagged "hard".

但问题是:我的解决方案在最坏的情况下也是线性的(因为添加/清除操作是线性的时间)。为什么 更慢?然后我这样做了:

But here comes the question: my solution is also linear at worst case (because add/clear operations are linear time). Why is it that slower? And then I did this:

    Comparator<Interval> comparator = new Comparator<Interval>() {
        @Override
        public int compare(Interval i1, Interval i2) {
            return Integer.compare(i1.start, i2.start);
        }
    };
    int start = Collections.binarySearch(intervals, newInterval, comparator);
    int skip = start >= 0 ? start : -start - 1;
    int end = Collections.binarySearch(intervals.subList(skip, intervals.size()),
                                       new Interval(newInterval.end, 0),
                                       comparator);

从80毫秒降至4毫秒!这里发生了什么?不幸的是,我不知道LeetCode运行的是什么样的测试,或者在什么环境下运行,但仍然不是20倍太多了?

From 80 ms down to 4 ms! What's going on here? Unfortunately I have no idea what kind of tests LeetCode runs or under what environment, but still, isn't 20 times too much?

推荐答案

您显然遇到了lambda表达式的首次初始化开销。正如在注释中已经提到的,lambda表达式的类是在运行时生成的,而不是从类路径加载。

You are obviously encountering the first-time initialization overhead of lambda expressions. As already mentioned in the comments, the classes for lambda expressions are generated at runtime rather than being loaded from your class path.

然而,生成的不是导致放缓。毕竟,生成具有简单结构的类甚至比从外部源加载相同的字节更快。内部类也必须加载。但是当应用程序之前没有使用过lambda表达式时,甚至必须加载用于生成lambda类的框架(Oracle的当前实现使用了ASM)。这是十几个内部使用的类的减速,加载和初始化的实际原因,而不是lambda表达式本身。

However, being generated isn’t the cause for the slowdown. After all, generating a class having a simple structure can be even faster than loading the same bytes from an external source. And the inner class has to be loaded too. But when the application hasn’t used lambda expressions before, even the framework for generating the lambda classes has to be loaded (Oracle’s current implementation uses ASM under the hood). This is the actual cause of the slowdown, loading and initialization of a dozen internally used classes, not the lambda expression itself.

您可以轻松验证这一点。在使用lambda表达式的当前代码中,您有两个相同的表达式(i1,i2) - > Integer.compare(i1.start,i2.start)。当前实现无法识别这一点(实际上,编译器也没有提供提示)。所以在这里,生成两个具有甚至不同类的lambda实例。你可以重构代码只有一个比较器,类似于你的内部类变体:

You can easily verify this. In your current code using lambda expressions, you have two identical expressions (i1, i2) -> Integer.compare(i1.start, i2.start). The current implementation doesn’t recognize this (actually, the compiler doesn’t provide a hint neither). So here, two lambda instances, having even different classes, are generated. You can refactor the code to have only one comparator, similar to your inner class variant:

final Comparator<? super Interval> comparator
  = (i1, i2) -> Integer.compare(i1.start, i2.start);
int start = Collections.binarySearch(intervals, newInterval, comparator);
int skip = start >= 0 ? start : -start - 1;
int end = Collections.binarySearch(intervals.subList(skip, intervals.size()),
                                   new Interval(newInterval.end, 0),
                                   comparator);

您不会注意到任何重大的性能差异,因为它不是重要的lambda表达式的数量,但只是框架的类加载和初始化,只发生一次。

You won’t notice any significant performance difference, as it’s not the number of lambda expressions that matters, but just the class loading and initialization of the framework, which happens exactly once.

你甚至可以通过插入额外的lambda表达式来最大化它,比如

You can even max it out by inserting additional lambda expressions like

final Comparator<? super Interval> comparator1
    = (i1, i2) -> Integer.compare(i1.start, i2.start);
final Comparator<? super Interval> comparator2
    = (i1, i2) -> Integer.compare(i1.start, i2.start);
final Comparator<? super Interval> comparator3
    = (i1, i2) -> Integer.compare(i1.start, i2.start);
final Comparator<? super Interval> comparator4
    = (i1, i2) -> Integer.compare(i1.start, i2.start);
final Comparator<? super Interval> comparator5
    = (i1, i2) -> Integer.compare(i1.start, i2.start);

没有看到任何减速。这是你在这里注意到的整个运行时的第一个lambda表达式的初始开销。由于Leetcode本身在输入代码之前显然不使用lambda表达式,其执行时间会被测量,这个开销会增加你的执行时间。

without seeing any slowdown. It’s really the initial overhead of the very first lambda expression of the entire runtime you are noticing here. Since Leetcode itself apparently doesn’t use lambda expressions before entering your code, whose execution time gets measured, this overhead adds to your execution time here.

参见Java lambda函数将如何编译?lambda表达式是否在每次执行时都会堆积?

这篇关于Java lambdas比匿名类慢20倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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