Cached Optional<Boolean> values

£可爱£侵袭症+ 提交于 2019-12-11 04:46:14

问题


There doesn't seem to be any cached objects of type Optional<Boolean> for the true and false values available in the standard library. Am I missing them somewhere?

It would surprise me if there were no such objects because it seems to me like this would be so useful, for both clarity and performance.

If there really are no such objects, why is that?


回答1:


There is no reason to fix a particular optimization strategy into the API. Optional instances are acquired via a factory method and it’s behavior regarding returned object identities is intentionally unspecified.

So implementations can have a caching facility internally but it may also be the case that the JVM’s optimizer takes care about such things. Today’s JVMs already elide instance creations in hotspots when possible, but future JVM implementations may also inject caching or de-duplication facilities for “value based classes”.

See also “Why should I not use identity based operations on Optional in Java8?”




回答2:


In Java 8, they have improved the optimisation of object creation, especially for short lived objects such as Optional. What the JIT can do is use Escape Analysis to eliminate short lived objects by placing their fields on the stack. In the case of Optional<Boolean> this can most likely be turned in no more than boolean

See the following article on object elimination, how to detect it is not working and what you can do about it. Java Lambdas and Low Latency

The converse question, is why have OptionalInt, OptionalLong and OptionalDouble? These are likely to be useful, just not as useful as you might think. Unlike Boolean not all Integer, Long and Double values are cached, and while Escape Analisys can eliminate objects, it is expensive and can take a while to kick in, possibly never for code not run long enough.



来源:https://stackoverflow.com/questions/28738231/cached-optionalboolean-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!