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

后端 未结 3 1263
天命终不由人
天命终不由人 2020-11-22 02:45

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

myStream.forEach(item -> {
  // do something useful
});
<
3条回答
  •  梦谈多话
    2020-11-22 02:48

    You are passing a new instance to the forEach method. Every time you do that you create a new object but not one for every loop iteration. Iteration is done inside forEach method using the same 'callback' object instance until it is done with the loop.

    So the memory used by the loop does not depend on the size of the collection.

    Isn't this equivalent to the 'old syntax' snippet?

    Yes. It has slight differences at a very low level but I don't think you should care about them. Lamba expressions use the invokedynamic feature instead of anonymous classes.

提交回复
热议问题