243. Optional<T> versus OptionalInt

If there is no specific reason for using boxed primitives, then it is advisable to avoid Optional<T> and rely on non-generic OptionalInt, OptionalLong, or OptionalDouble type.

Boxing and unboxing are expensive operations that are prone to induce performance penalties. In order to eliminate this risk, we can rely on OptionalInt, OptionalLong, and OptionalDouble. These are wrappers for the int, long, and double primitive types.

So, avoid the following (and similar) solutions:

// Avoid
Optional<Integer> priceInt = Optional.of(50);
Optional<Long> priceLong = Optional.of(50L);
Optional<Double> priceDouble = Optional.of(49.99d);

And prefer the following solutions:

// Prefer
// unwrap via getAsInt()
OptionalInt priceInt = OptionalInt.of(50);

// unwrap via getAsLong()
OptionalLong priceLong = OptionalLong.of(50L);

// unwrap via getAsDouble()
OptionalDouble priceDouble = OptionalDouble.of(49.99d);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.2.157