英文:
Java: does lambda usage has negative influence on performance or memory use
问题
在Java中使用lambda表达式,例如在调用collection.removeIf(item -> item.isOptionSet())
时,与显式编写代码相比,是否对性能或内存使用造成明显的负面影响?
从性能和内存使用的角度来看,上述的lambda表达式与以下代码类似:
collection.removeIf(new Predicate<Item>() {
@Override
public boolean test(Item item) {
return item.isOptionSet();
}
});
英文:
Does using lambdas in Java, e.g. when invoking collection.removeif(item -> item.isOptionSet())
, has any noticable negative impact on performance or memory usage compared to writing it explicitly
for (Iterator it = collection.iterator(); it.hasNext();) {
if (it.next().isOptionSet()) {
it.remove();
}
}
From a performance/memory point of view, is the above lambda similar to
collection.removeIf(new Predicate<Item>() {
@Override
public boolean test(Item item) {
return item.isOptionSet();
}
});
?
答案1
得分: 2
关于内存方面没有太大的差异。
在性能方面,一切取决于即时编译器(JIT compiler)所执行的优化级别,这取决于许多因素,比如使用的 JVM、JVM 版本,以及代码运行的频率和次数等。在 lambda 最初推出时,它们的速度较慢,因为 JVM 开发人员尚未能够优化其性能。即使在今天,我猜循环是最快的,然后是匿名类,然后是 lambda,但正如我所说,通过足够的编译代码优化(方法内联、栈分配等),你最终可能会得到相同的结果。
英文:
In terms of memory not much difference.
In terms of performance, it all depends on the level of optimization that is performed by the JIT compiler, which depends on many things, such as the Jvm being used, the Jvm version, and the frequency and count of how often the code is run. In the early days of lambdas they were slower because Jvm developers had not yet been able to optimize their performance. Even today I would guess that the loop is fastest, then the anonymous class, then the lambda, but as I said with enough optimization in the compiled code (method inclining, stack allocation, etc) you may end up with the same thing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论