RFE: Refactor java.util.Optional and add NonNull checks
Quân Anh Mai
anhmdq at gmail.com
Mon Aug 28 08:13:04 UTC 2023
Hi,
Polymorphism is a performance killer. Normally this does not matter much,
but for thin wrappers such as Optional, this is one of the most important
factor.
Behaviour polymorphism requires virtual dispatch and prevents inlining.
This is really detrimental, as simple operations such as a getter which is
previously only consisted of a memory load, in the presence of polymorphism
would have to go through a 10-time more expensive virtual dispatch.
Function calls, especially virtual ones, are also opaque and prohibit
compiler optimisations.
Layout polymorphism prevents direct accesses and requires indirection. This
means that for every instance of Optional created a memory allocation is
required. Optional is expected to be a near zero-cost abstraction in the
presence of Value classes, so making it polymorphic is unacceptable.
Thanks.
On Wed, 23 Aug 2023 at 22:43, Oleksii Kucheruk <iselo+openjdk at raccoons.co>
wrote:
> Hi there.
> I have found that `java.util.Optional` is written procedural style and has
> `ifnonnull` checks in each method. I propose to refactor `Optional` in
> accordance to OOP-style. This will eliminates all unnecessary
> `if`-statements, removes duplications and reduces bytecode size more then
> twice.
>
> I have two solutions:
> 1. Completely dynamic that avoids single static `EMPTY` instance and
> unchecked casting of each `Optional.empty()`
> 2. Preserving original single static `EMPTY` per VM.
>
> Also there are couple methods that throws NPE due to calling methods on
> null-objects and requires to add `Objects.requireNonNull(...)`.
>
> OptionalInt, OptionalDouble, OptionalLong could be refactored same way
> even with remove of additional boolean variable `isPresent`.
>
> Since I'm new here any guidance will be helpful.
> Thank you in advance.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20230828/39623dac/attachment.htm>
More information about the core-libs-dev
mailing list