DEV Community


Posted on

Performance matters


Good performance starts with good code.

Sometimes a small change in your code can make a significant amount of performance improvement.
So let not your code stink, be careful next time while you write code.

The API of Optional typically has two methods that can cause confusion: orElse() and orElseGet().

1.  public T orElse(T other)
2.  public T orElseGet(Supplier<? extends T> other)

Clearly, orElse() takes any parameter of a type T whereas orElseGet() accepts a functional interface of type Supplier that returns an object of type T.

Now, based on their Javadocs:

. orElse(): returns the value if present, otherwise return other
. orElseGet(): returns the value if present, otherwise invoke other and return the result of its invocation


orElse() is evaluated even when having a non-empty Optional.
For example,

String name = Optional.of("")

public String processData() {"process data method - start");
    // DB process/update complex business logic 
"processData method - end");
    return "processed string";

On executing our code, we'll find below messages printed in the console:

process data method - start
processData method - end

The variable name will hold at the end of the code execution.

With it, we can easily infer that the parameter of orElse() is evaluated even when having a non-empty Optional. It can easily cause Hugh performance downgrade if else part is having some DB processing or complex business logic.


Now, let's try writing similar code using orElseGet()

String name = Optional.of("")
  .orElseGet(() -> processData());

public String processData() {"process data method - start");

    // DB process/update heavy processing"processData method - end");
    return "processed string";

The above code will not invoke processData() method.

Using orElseGet() for our case will, therefore, save us some time involved in computing.

So to summarize this blog we can considering factors involve.

  • What if the method would execute some additional logic? E.g. making some DB inserts or updates

  • Even when we assign an object to orElse() parameter

String name = Optional.of("")

we're still creating “Other” object for no reason

And that's why it is important for us to make a careful decision among orElse() and orElseGet() depending on our needs – by default, it makes more sense to use orElseGet() every time unless the default object is already constructed and accessible directly.

Top comments (1)

dhareppahm profile image
Dhareppa Metri

Really helpful. Thanks for sharing.