Java: lambda usage有否对性能或内存使用造成负面影响

huangapple go评论80阅读模式
英文:

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 -&gt; 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&lt;Item&gt;() {
  @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.

huangapple
  • 本文由 发表于 2020年10月26日 21:11:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64537819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定