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

orElse Evaluation: Always Executes

Understand that orElse always evaluates its argument, even when the Optional contains a value, and performance implications.

orElse Evaluation: Always Executes

You'll learn why orElse() can create unexpected performance problems even when your Optional contains a value.

The Core Problem

When you call orElse(value) on an Optional, Java always evaluates the argument you pass in—regardless of whether the Optional is empty or not. This happens because method arguments in Java are evaluated before the method is called.

The Hidden Cost

Consider this scenario:

Optional<String> opt = Optional.of("exists");
String result = opt.orElse(expensiveDefaultValue());

Even though opt contains "exists", the method expensiveDefaultValue() still runs. The JVM evaluates it, gets the result, passes it to orElse(), and then orElse() simply ignores it because the Optional isn't empty.

Real-World Impact

Think of it like ordering a backup pizza "just in case" your main pizza doesn't arrive—but you order and pay for the backup pizza before you even know if the main one is coming. Even if the main pizza arrives, you've already spent the money.

// This ALWAYS creates a new list, even if cached is present
Optional<List<String>> cached = getFromCache();
List<String> data = cached.orElse(new ArrayList<>()); // ❌ ArrayList created every time

// This ALWAYS queries the database, even if user is present
Optional<User> user = findInMemory(id);
User result = user.orElse(queryDatabase(id)); // ❌ Database hit every time!

When orElse Is Fine

orElse() works great when the default value is cheap: a literal, a constant, or a simple variable reference.

String name = optName.orElse("Unknown"); // ✓ Fine - string literal
int count = optCount.orElse(0); // ✓ Fine - primitive constant

Key Takeaway: orElse() always evaluates its argument eagerly, making it unsuitable for expensive default value computations. Use it only with cheap, pre-computed values.