Does a lambda expression create an object on the heap every time it’s executed?

When I iterate over a collection using the new syntactic sugar of Java 8, such as

myStream.forEach(item -> {
  // do something useful
});

Isn’t this equivalent to the ‘old syntax’ snippet below?

myStream.forEach(new Consumer<Item>() {
  @Override
  public void accept(Item item) {
    // do something useful
  }
});

Does this mean a new anonymous Consumer object is created on the heap every time I iterate over a collection? How much heap space does this take? What performance implications does it have? Does it mean I should rather use the old style for loops when iterating over large multi-level data structures?

3 Answers
3

Leave a Comment