Looking at the source code for java.util.OptionalInt
, an optional int is made of an int value
and a boolean isPresent
. The only way of obtaining an empty optional int is through the OptionalInt.empty()
method which returns OptionalInt.EMPTY
, the common instance for all empty optional ints.
If this is the case, then why is the isPresent()
method implemented as return isPresent
rather than this == EMPTY
and reducing memory usage by getting rid of the isPresent
field?
In Java, an OptionalInt object is a container object that may or may not contain an integer value. The OptionalInt class is present in the java. util package. The getAsInt() method is used to get the integer value present in an OptionalInt object.
Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.
It's an implementation choice and the only people who can give a clear answer are the people who wrote the implementation.
But very likely it's a choice that puts readability, clarity and maintainability of code over memory micro optimizations.
It really doesn't make much sense to be worried about the space a boolean takes up in an object that wraps an int. If that space is relevant, an OptionalInt
shouldn't be used in the first place, (or Java for that matter,) considering the object header needs at least 8 bytes (on 32 bit JVMs, more on 64 bit) already.
Java isn't for writing memory constrained applications, it's for writing easily maintainable code. And implementing isPresent()
as getter for isPresent
is easier to read, less error prone when refactoring and fits with established Java coding practices.
On a side note: Since Java objects are 8 byte aligned it probably doesn't even make the class smaller when you remove As Eugene pointed out in a comment, it actually does increase the size, as the field isPresent
.isPresent
lies right on the boundary and then 7 more bytes are added for padding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With