Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional vs if/else-if performance java 8

Hello i have two samples of code

if/else if/else statements

private Object getObj(message) {
        if (message.getA() != null)
            return message.getA();
        else if (message.getB() != null)
            return message.getB();
        else if (message.getC() != null)
            return message.getC();
        else return null;
}

Optional statements

private Optional<Object> wrap(Object o){
    return Optional.ofNullable(o);
}

private Object getObj(message) {
    return  wrap(message.getA())
            .orElseGet(() -> wrap(message.getB())
            .orElseGet(() -> wrap(message.getC())
            .orElse(null)));
}

So my question is how these two compare in terms of performance (i have about 15-20 if-else statements on actual code)?

Is it worth refactoring the code readability vs performance or is a misusage of optionals?

Also what is the performance penalty in case the if/else-if statements grown to 100+?

Thanks in advance

like image 933
Panos K Avatar asked May 21 '19 09:05

Panos K


People also ask

What is the main advantage of Optional in Java 8?

Java 8 has introduced a new class Optional in java. util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException .

How do I replace if else with Optional?

How to change this if into Optional? It might be better to take advantage of method overloading in this case, so that the check() method with no parameter calls doMore(), while the check() method with the @NonNull String name only accepts non-null Strings. Otherwise, follow either Eugene's or luk2302's suggestions.

What is the difference between orElse and orElseGet?

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

Should Java 8 getters return Optional type?

As for your getters, don't use Optional. And try to design your classes so none of the members can possibly be null.


Video Answer


2 Answers

Don't use Optionals for conditional logic.

They were designed, to be returned from a method to indicate a potentially absent value.

Just because you can nicely chain them into a single line doesn't mean that it's understandable. Also you literally gain nothing. The performance overhead may be significant. In the worst case N objects being created and then discarded. Just stay with your "normal" if-else chains.


Instead of finding ways to make your current code more readable, take a step back and ask yourself why you need 15-20 if-else statements. Can you split some logic up? Why do you need a getter for so many different fields with potentially different types in the first place? etc.

like image 115
Lino Avatar answered Nov 09 '22 01:11

Lino


There is a third form (allowing still some variation).

return Stream.<Supplier<Object>>of(message::getA, message::getB, message::getC)
        .map(Supplier::get)
        .filter(Objects::nonNull)
        .findFirst()
        .orElse(null);

Probably the least flexible and efficient at this moment, but clear.

like image 21
Joop Eggen Avatar answered Nov 09 '22 03:11

Joop Eggen