是否可以重用Java Lambda匿名对象? [英] Is Java lambda anonymous object reused?

查看:123
本文介绍了是否可以重用Java Lambda匿名对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从当前的JDK 1.8实现开始,它构建一个匿名对象来保存lambda函数,并在该对象上调用该函数.这个匿名对象是在每次调用中重用,还是每次都重新创建一个对象?

As of the current JDK 1.8 implementation, it builds an anonymous object to hold the lambda function and calls the function on such object. Is this anonymous object reused in each call, or is an object re-created each time?

推荐答案

它可能会被重复使用,可能不会.

It may be re-used, it may not.

来自 JLS 15.27. 4 :

具有以下属性的类的新实例是 分配和初始化,或者类的现有实例 引用了以下属性.

Either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced.

您不能依靠它成为另一个.编译器和/或运行时可以选择提供最佳结果的程序. (这是lambda相对于匿名类的好处之一-因为每次使用new,即使在匿名类上,也保证它是一个新对象,他们无法通过重用它来对其进行优化,即使您有99%的时间都不在乎它们是否是同一对象.)

You cannot depend on it to be one or the other. The compiler and/or runtime can choose the one that will give the best result. (This is one of the benefits of lambdas over anonymous classes -- because every time you use new, even on an anonymous class, it is guaranteed to be a new object, they are unable to optimize it by re-using it, even though 99% of the time you don't care if they are the same object or not.)

在lambda从周围的范围捕获变量的情况下,通常无法重用该对象,因为捕获的变量的值是存储在lambda对象中的状态,并且每次对lambda进行求值(即使它与源代码中的lambda相同),也可能捕获捕获变量的不同值.只有编译器可以以某种方式保证lambda的两个特定求值必须捕获变量的完全相同的值时,编译器才可以重用该对象.

In the case where the lambda captures variables from the surrounding scope, it is generally not possible to re-use the object because the value of the captured variables is state stored in the lambda object, and each time the lambda is evaluated (even if it's the same lambda in source code), it may capture different values of the captured variables. Only if the compiler can somehow guarantee that two particular evaluations of the lambda must capture the exact same value of variables, can the compiler re-use the object.

如果lambda不捕获任何变量,则该lambda的所有实例在行为上都是相同的.因此,在这种情况下,可以将单个对象重新用于该lambda的所有评估.我相信在这种情况下,Java的当前实现只在程序执行期间分配了一个副本.但这只是依赖于实现的优化.

In the case where the lambda does not capture any variables, then all instantiations of that lambda are identical in behavior. So in this case, a single object can be re-used for all evaluations of that lambda. I believe that the current implementation of Java does only allocate one copy for the duration of the program in this case. But this is just an optimization that is implementation-dependent.

这篇关于是否可以重用Java Lambda匿名对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆