java.util.Optional: a better implementation?

Remi Forax forax at
Wed Oct 29 13:10:43 UTC 2014

On 10/29/2014 01:43 PM, Aleksey Shipilev wrote:
> On 29.10.2014 15:25, David Holmes wrote:
>> On 29/10/2014 10:06 PM, nicarran at wrote:
>>> The JVM probably optimizes and throws away the null checks yielding in
>>> equal performance compared to the proposed implementation (above) ---I
>>> haven't done any performance tests----, but why wait for the JVM when
>>> this implementation is also nicer to read? What do you think?
> I think most of the null checks will be folded into implicit null
> checks, which will have null (pun intended) effect on performance. What
> you suggest, however, will probably explode otherwise monomorphic calls
> to Optional to bimorphic calls to Optional.Empty/Optional.present -- and
> that will affect performance.
> You can make a few benchmarks to quantify those effects -- out of
> curiosity. I don't think the minute improvements, if any, will justify
> exploding the class hierarchy though.
> -Aleksey.

The first implementation of Optional was roughly the one you suggest, it 
was later change to the current implementation which is, as everybody, 
said faster and will let the VM to remove the boxing (the object 
corresponding to Optional) in a future version of Java
and please don't use Optional all around your code but only in public API :)


More information about the core-libs-dev mailing list