Optional vs if/else-if performance java 8

前端 未结 5 1751
我寻月下人不归
我寻月下人不归 2021-02-19 22:58

Hello i have two samples of code

if/else if/else statements

private Object getObj(message) {
        if (message         


        
5条回答
  •  既然无缘
    2021-02-20 00:00

    tl;dr

    If your goal is condensed code, then use ternary chaining. Performance is likely identical to that of a series of if-then-else statements.

            ( this.getA() != null ) ? this.getA()
                    : ( this.getB() != null ) ? this.getB()
                    : ( this.getC() != null ) ? this.getC()
                    : null;
    

    Ternary chaining

    As the Answer by Lino correctly states, you are trying to take Optional beyond their original design purpose (returning values within lambdas & streams). Generally best to use Optional only with a return statement, and only then when you want to make clear that null is a valid value to be returned. See this Answer by Brian Goetz.

    A ternary operator is a condensed if-then-else, combined into a one-liner.

    result = test ? valueToUseIfTestIsTrue : valueToUseIfTestIsFalse
    

    Example:

    Color color = isPrinterMonochrome ? Color.GREY : Color.GREEN ; 
    

    Use a chain of ternary statements.

    So this:

        if ( this.getA() != null )
            return this.getA();
        else if ( this.getB() != null )
            return this.getB();
        else if ( this.getC() != null )
            return this.getC();
        else return null;
    

    …becomes this:

        return
                ( this.getA() != null ) ? this.getA()
                        : ( this.getB() != null ) ? this.getB()
                        : ( this.getC() != null ) ? this.getC()
                        : null;
    

    Example code.

    public String getA ()
    {
        // return "A";
        return null;
    }
    
    public String getB ()
    {
        // return "B";
        return null;
    }
    
    public String getC ()
    {
        return "C";
        // return null;
    }
    
    public String getABC ()
    {
        if ( this.getA() != null )
            return this.getA();
        else if ( this.getB() != null )
            return this.getB();
        else if ( this.getC() != null )
            return this.getC();
        else return null;
    }
    
    public String getABCTernary ()
    {
        return
                ( this.getA() != null ) ? this.getA()
                        : ( this.getB() != null ) ? this.getB()
                        : ( this.getC() != null ) ? this.getC()
                        : null;
    }
    

    Run that example code.

    String s = this.getABCTernary();
    System.out.println( "s: " + s );
    

    C

    Pros and cons

    • The upside to the ternary chain is condensed code, collapsed into a one-liner.
    • The downside is that you are calling your getter method twice in this particular situation just to get a single value. Not a problem for a simple fetch-the-variable kind of getter, but impact performance if the getter is a time-consuming method such as a remote web services call. And, the cascading if-then-else has the same problem, also calling your getter twice.

    Performance

    how these two compare in terms of performance

    The ternary operator in Java is "short-circuiting", meaning the left or right side that matches the test results is the only code called. In our code here, if getA returns a non-null value, that value is returned immediately. The further calls to getB and getC are never executed. So in this regard, the performance of the chained ternary is the same as a cascading if-then-else statement: first-match wins, no further calls.

    If you mean performance as in nanoseconds of execution, I do not know. Worrying about that would be falling into the trap of premature optimization. Modern JVMs are extremely well-tuned for optimizing your code.

提交回复
热议问题