Optional.orElse() vs Optional.orElseGet()

1. Introduction

This article is part of ongoing series of Optional. Read about it more here.

orElse(T defaultValue) method returns the value from Optional if value is present else it returns the default value passed in its parameter.

orElseGet(Supplier<? extends T> supplier) method is similar to orElse method. The only difference is orElseGet method accepts Supplier of result. orElse method accepts result itself. 

2. Which method to use when?

MethodScenario
orElse(T defaultValue)If default object already created and accessible to you then use this method.
orElseGet(Supplier<? extends T> supplier)If default object is not created and not accessible to you and/or creating the object can have a performance impact, then use this method.
Prefer Method Reference to Lambda Expression.
Performance impact must be measured using benchmarks. 

3. Lambda vs Method Reference

Using Lambda instead of Method Reference in orElseGet can cause a very small overhead in first call. This is when a method needs to be created to represent lambda.

Method reference is faster than Lambda because method already exists, just a handle is used to point to the method.

Consider below example :

Optional<Money> optMoney = 
	txns.stream()
		.map(txn -> txn.getInvoice())
		.filter(invoice -> invoice.invoiceId().equals(invoiceId))
		.map(invoice -> invoice.invoiceTotal())
		.findAny();
 
Money value = optMoney.orElse(Money.zero(CurrencyUnit.USD));
 
Money value = optMoney.orElseGet(()->Money.zero(CurrencyUnit.USD));

Now assume that Optional is empty and Supplier of Money will create a new instance and return it. In addition to that a method for lambda would also be created. Subsequent calls wouldn’t incur time cost for creating a method.

In comparison, if we use orElse(T defaultValue) then regardless of Optional is empty or not the defaultValue will be instantiated. This can deteriorate in time, how much time? That depends on the number of calls coming into Optional.

It is better to generally use orElseGet in comparison to orElse. Also, it is better to use method reference instead of Lambda.

4. Conclusion

In this article we covered the difference between orElse and orElseGet method and when to use either of them. 

Leave a Reply

Your email address will not be published. Required fields are marked *