Java Optional: orElse() vs orElseGet()
orElse
and orElseGet
are useful methods that allow us to handle the case of having a null value in an Optional. As it is possible to encounter performance issues in some cases, it is important to understand how those methods work before choosing one. Let’s begin by checking the methods’ signatures first.
As you see above, while the orElse()
method accepts a value to be returned when the optional value is empty, the orElseGet()
method accepts a Supplier
functional interface that provides a value to be returned when the optional is empty.
Let’s have a look at our first example below.
Let’s assume we need to use the shipping address that exists in an external resource when the billing address is empty while preparing an invoice.
And this is the method that provides the shippingAddress:
As getShippingAddress()
method will be executed regardless of whether billingAddress
is empty, the total code execution time won’t be less than the execution time of the getShippingAddress() method.
Let’s closely look at the following test executions:
As you see, all test executions took a bit longer than the value of Thread.sleep()
call in getShippingAddress()
method.
But, what about orElseGet()
method?
Let’s modify our test code a bit and use orElseGet()
instead.
It seems like something has changed a bit. While the first test case took 7 ms, the second one took about ~500 ms. Because it’s pretty simple. orElseGet() hasn’t executed the supplier function that calls getShippingAddress()
method unless the optional billingAddress
is empty.
Conclusion
In conclusion, it’s important to understand how both of these useful methods work before deciding which one to use. It might be a better option to prefer orElseGet
unless the default value is already instantiated.
Thanks for reading!