DEV Community

Sumit
Sumit

Posted on

Performance matters

Performance

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)
Enter fullscreen mode Exit fullscreen mode

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()

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

String name = Optional.of("dev.to")
  .orElse(processData());

public String processData() {
    LOG.info("process data method - start");
     
    // DB process/update complex business logic 
     
    LOG.info("processData method - end");
    return "processed string";
}
Enter fullscreen mode Exit fullscreen mode

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

process data method - start
processData method - end
Enter fullscreen mode Exit fullscreen mode

The variable name will hold dev.to 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.

orElseGet()

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

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

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

    // DB process/update heavy processing 

    LOG.info("processData method - end");
    return "processed string";
}
Enter fullscreen mode Exit fullscreen mode

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("dev.to")
.orElse("Other");

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)

Collapse
 
dhareppahm profile image
Dhareppa Metri

Really helpful. Thanks for sharing.