1

I have a service that return a OptionalDouble, if it is null i return a value from another service, but I don't know if it is better orElseGet or orElse in terms of performance or best practices..

Option1)

fixerService.getRate(addWalletAmount.getMenuSymbol())
                                    .orElseGet(() -> menuService
                                                    .findBySymbol(addWalletAmount
                                                            .getMenuSymbol())   
                                                            .getPrice()
                                                            .doubleValue());

Option2)

 fixerService.getRate(addWalletAmount.getMenuSymbol())
                                    .orElse(menuService
                                                    .findBySymbol(addWalletAmount
                                                            .getMenuSymbol())   
                                                            .getPrice()
                                                            .doubleValue());
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301

1 Answers1

2

Of course orElseGet() is preferable. orElse() would execute your service even when the OptionalDouble is not empty, which is wasteful (since menuService.findBySymbol(addWalletAmount.getMenuSymbol()).getPrice().doubleValue() is the argument passed to the orElse() method, and it must be evaluated before orElse() is executed).

orElseGet() would only execute your service if the OptionalDouble is empty.

Eran
  • 387,369
  • 54
  • 702
  • 768