When to use Optional.orElse() rather than Optional.orElseGet()

  • A+
Category:Languages

I've read the answers to this question about the difference between Optional.orElse() and Optional.orElseGet().

It seems that orElseGet() is always more efficient than orElse() because of lazy evaluation, and it's apparently visible even when benchmarking very simple examples like this one (see part 4): https://www.baeldung.com/java-optional-or-else-vs-or-else-get

So, are there any use cases where it's better to use orElse rather than orElseGet?

 


  1. In most cases, you type less when using orElse, since it is shorter than orElseGet and, compare the signatures of them:

orElse(T other) orElseGet(Supplier<? extends T> other) 

a Supplier<? extends T> other is most likely longer than T other. If the performance is not so critical you may choose to type less. Programmer's effort also counts :-) For example, compare:

orElseGet(() -> 1) orElse(1) 
  1. As your link has mentioned:

by default, it makes more sense to use orElseGet() every time unless the default object is already constructed and accessible directly.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: