Java 8 lambdas 和匿名内部类之间的性能差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24294846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Performance difference between Java 8 lambdas and anonymous inner classes
提问by csvan
Before Java 8, lambda functionality could be achieved by using anonymous inner classes. For example:
在 Java 8 之前,可以通过使用匿名内部类来实现 lambda 功能。例如:
interface Lambda {
void doStuff();
}
// ...
public void doWithCallback(Lambda callback) {
// ...
callback.doStuff();
}
// ...
doWithCallback(new Lambda {
public void doStuff() {
// ...
}
});
In terms of performance, is there a difference between still using this approach and using the new Java 8 lambdas?
在性能方面,仍然使用这种方法和使用新的 Java 8 lambdas 有区别吗?
采纳答案by dkatzel
Oracle has posted a study comparing performance between Lambdas and anonymous classes
Oracle 发布了一项比较 Lambda 和匿名类之间性能的研究
See JDK 8: Lambda Performance Studyby Sergey Kuksenko, which is 74 slides long.
请参阅Sergey Kuksenko 的JDK 8:Lambda 性能研究,它有 74 张幻灯片。
Summary: slow to warm up but when JIT inlines it worst case just as fast as anonymous class but can be faster.
总结:预热很慢,但是当 JIT 内联时,最坏的情况是与匿名类一样快,但可以更快。
回答by Arseny
As I found, the iterating over array with Stream is working much slower (74 slides are not consider such the case). I think that it is not the only performance leaks in lambdas (guess, it will be improved in the future). The example below was running with Java 8 without any options:
正如我发现的那样,使用 Stream 迭代数组的工作速度要慢得多(74 张幻灯片不考虑这种情况)。我认为这不是 lambdas 中唯一的性能泄漏(猜测,将来会改进)。下面的示例在没有任何选项的情况下使用 Java 8 运行:
//Language is an enum
Language[] array = Language.values();
System.err.println(array.length); // 72 items
long t = System.nanoTime();
for (Language l : array) System.out.println(l.getLanguageName());
System.err.println(System.nanoTime()-t); //nano time 1864724
t = System.nanoTime();
Arrays.stream(array).forEach(v -> System.out.println(v.getLanguageName()));
System.err.println(System.nanoTime()-t); //nano time 55812625 (55812625/1864724 = 29.93 times longer)
List<Language> list = Arrays.asList(array);
t = System.nanoTime();
for (Language l : list) System.out.println(l.getLanguageName());
System.err.println(System.nanoTime()-t); //nano time 1435008
t = System.nanoTime();
list.forEach(v -> System.out.println(v.getLanguageName()));
System.err.println(System.nanoTime()-t); //nano time 1619973 (1619973/1435008 = 1.128 times longer)