问题
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