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

后端 未结 3 1253
天命终不由人
天命终不由人 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 02:48

    It is equivalent but not identical. Simply said, if a lambda expression does not capture values, it will be a singleton that is re-used on every invocation.

    The behavior is not exactly specified. The JVM is given big freedom on how to implement it. Currently, Oracle’s JVM creates (at least) one instance per lambda expression (i.e. doesn’t share instance between different identical expressions) but creates singletons for all expressions which don’t capture values.

    You may read this answer for more details. There, I not only gave a more detailed description but also testing code to observe the current behavior.


    This is covered by The Java® Language Specification, chapter “15.27.4. Run-time Evaluation of Lambda Expressions”

    Summarized:

    These rules are meant to offer flexibility to implementations of the Java programming language, in that:

    • A new object need not be allocated on every evaluation.

    • Objects produced by different lambda expressions need not belong to different classes (if the bodies are identical, for example).

    • Every object produced by evaluation need not belong to the same class (captured local variables might be inlined, for example).

    • If an "existing instance" is available, it need not have been created at a previous lambda evaluation (it might have been allocated during the enclosing class's initialization, for example).

提交回复
热议问题