What is faster: many ifs, or else if?

后端 未结 11 1780
夕颜
夕颜 2020-12-29 22:35

I\'m iterating through an array and sorting it by values into days of the week.

In order to do it I\'m using many if statements. Does it make any differ

11条回答
  •  长发绾君心
    2020-12-29 23:08

    This question is specially interesting when the if block returns thus finishing the method. It also applies directly to the way comparators in Java work.

    I've thus run each method (bellow) 250.000.000 times and the results are as follows:

    two values   if/else    - 6.43 millis
    three values if/else/if - 8.66 millis
    three values if/if      - 9.01 millis
    

    While the worst case takes 1.4 times longer than the best one do notice that this is the aggregate sum of iterating each one of these methods 250 million times. Assuming that it would take 100ms for a human to perceive delay and that the worst/better difference is 2.58 millis it would imply that you would need almost a trillion (1000 * 1000 millions) iterations to perceive the difference between different methods.

    Summing it up: use if-else it's one of those cases where the fastest option is also the one with more legibility and less error-prone.

    // methods used to measure difference between if and if/else
    
    /** equality is not important **/
    private static int comparatorOfIfElse(int a, int b) {
        if(a < b) return -1;
        else return  1;
    }
    
    /** equality is taken into account using if/else **/
    private static int comparatorOfIfElseIf(int a, int b) {
        if(a < b) return -1;
        else if(a > b) return  1;
        return 0;
    }
    
    /** equality is taken into account using only if **/
    private static int comparatorOfIf(int a, int b) {
        if(a < b) return -1;
        if(a > b) return  1;
        return 0;
    }
    

提交回复
热议问题