-1

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();
  }
});

?

Thomas S.
  • 5,804
  • 5
  • 37
  • 72

1 Answers1

2

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.

Sean F
  • 4,344
  • 16
  • 30
  • I would have expected the anonymous class to be the slowest one. But I haven't looked at the byte code level. – Thomas S. Oct 26 '20 at 16:52
  • 1
    Well, the anonymous class does introduce a virtual method invocation, but even then when the jit realizes there is no possibility of the invocation being overridden with a subtype then the jit will inline the method, at which point the code may look identical to the loop. This is at the machine code level while the JVM is running, not the bytecode level. – Sean F Oct 26 '20 at 19:48