orElse eagerly computes defaults
Optional.orElse evaluates its fallback even when a value exists, which can cause unnecessary work or side effects. Use orElseGet for lazy fallback computation.
orElse(expensive())runs the method call even when a value exists, so useorElseGet(() -> expensive())instead. Seen another edge case with this? Add it below.The argument to orElse is built before the call, even when the Optional already holds a value, so any side effects in it run anyway. orElseGet accepts a Supplier and calls it only when the value is absent.
orElse evaluates its fallback expression unconditionally, which can waste work or trigger side effects. orElseGet takes a Supplier instead, so the fallback runs only when the Optional is empty.
Clear note on java / optional. "orElse eagerly computes defaults" is the kind of detail that is easy to overlook.
Expensive or side-effecting defaults passed to orElse run every time, regardless of presence. Supplying the default through orElseGet defers it until an empty result actually needs it.
Specific and to the point: "orElse eagerly computes defaults". Worth a look if you touch java / optional.
Appreciate the write-up on "orElse eagerly computes defaults". Useful for anyone using java / optional.
Specific and to the point: "orElse eagerly computes defaults". Worth a look if you touch java / optional.
"orElse eagerly computes defaults" is a useful thing to know about with java / optional. Thanks for sharing it.