Anti-Pattern: Overusing orElse with Expensive Operations
You'll learn why orElse can hurt performance when you pass expensive operations, and when to use orElseGet instead.
The Hidden Cost of orElse
Remember that orElse always evaluates its argument, regardless of whether the Optional is empty or not. This becomes problematic when you pass expensive operations:
Optional<String> config = getConfig("theme");
// BAD: Database call happens EVERY time
String theme = config.orElse(fetchDefaultFromDatabase());
// BAD: Object creation happens even when not needed
String value = optional.orElse(new ExpensiveObject().getValue());
// BAD: Complex computation runs unnecessarily
int result = optionalInt.orElse(calculateComplexDefault());
Even when config contains a value, fetchDefaultFromDatabase() still executes—you just throw away its result!
The Solution: orElseGet for Expensive Operations
Use orElseGet with a Supplier to defer execution until actually needed:
// GOOD: Database call only happens when Optional is empty
String theme = config.orElseGet(() -> fetchDefaultFromDatabase());
// GOOD: Object created only when needed
String value = optional.orElseGet(() -> new ExpensiveObject().getValue());
// GOOD: Computation runs only if Optional is empty
int result = optionalInt.orElseGet(() -> calculateComplexDefault());
The Rule of Thumb
Use orElse for: Simple constants or pre-computed values
config.orElse("default")
config.orElse(existingVariable)
Use orElseGet for: Method calls, object creation, or any computation
config.orElseGet(() -> computeDefault())
Think of orElse like paying for food whether you eat it or not, while orElseGet only charges you when you actually order.
Key Takeaway: Always use orElseGet instead of orElse when the default value requires method calls, object instantiation, or computation—orElse evaluates its argument eagerly, wasting resources even when the Optional contains a value.