java对象的重用,是否可以重用Java 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.

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.

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.)

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值