Course contentsShow
← Java
Lesson 1789 of 2,87037. Optional for Null SafetyFree lesson

Performance Comparison: orElse vs orElseGet

Analyze concrete performance differences with benchmarks showing when eager orElse evaluation impacts versus lazy orElseGet.

Performance Comparison: orElse vs orElseGet

What you'll learn: You'll understand the concrete performance impact of orElse's eager evaluation versus orElseGet's lazy evaluation through benchmark analysis.

The Performance Gap

While both orElse and orElseGet provide default values for empty Optionals, their evaluation strategies create measurable performance differences. The key distinction: orElse always computes its argument, even when the Optional contains a value.

When Performance Matters

Consider these scenarios:

Cheap computation (like a literal or existing variable):

optional.orElse("default")  // Negligible difference
optional.orElseGet(() -> "default")

Performance impact: microseconds or less — both are fine.

Expensive computation (like object creation or method calls):

optional.orElse(new ExpensiveObject())  // ALWAYS creates object
optional.orElseGet(() -> new ExpensiveObject())  // Creates ONLY if empty

Performance impact: significant — if Optional contains a value, orElse wastes CPU/memory creating an object that's immediately discarded.

Benchmark Insight

In real-world benchmarks with expensive operations:

  • When Optional is empty: Both perform identically (computation runs either way)
  • When Optional contains a value: orElseGet can be 10-100x faster depending on the default value's cost

The analogy: orElse is like ordering a backup pizza "just in case" — you pay for it whether you eat it or not. orElseGet only places the order if your main pizza doesn't arrive.

The Rule of Thumb

Use orElse for constants or pre-computed values. Use orElseGet for any computation, method call, or object construction. When in doubt, orElseGet is the safer choice.

Key Takeaway: orElseGet provides lazy evaluation that avoids unnecessary computation, delivering substantially better performance when the default value is expensive to create and the Optional frequently contains a value.