What is faster: many ifs, or else if?

后端 未结 11 1604
夕颜
夕颜 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;
    }
    
    0 讨论(0)
  • 2020-12-29 23:09

    To be honest I don't think it would matter which way you do it in terms of performance, I doubt you would see any difference. I would recommend using a switch statement which isn't a performance enhancment, simply syntactically nicer:

    switch ($day) 
    {
        case "Monday":
            // do something with Monday
            break;
        case "Tuesday":
            // do something with Tuesday
            break;
        case "Wednesday":
            // do something with Wednesday
            break;
    }
    
    0 讨论(0)
  • 2020-12-29 23:10

    Yes, use an else if, consider the following code:

    if(predicateA){
      //do Stuff
    }
    if(predicateB){
      // do more stuff
    }
    

    of

    if(predicateA){
      //
    }
    else if(predicateB){
      //
    }
    

    in the second case if predicateA is true, predicateB (and any further predicates) will not need to be evaluated (and so the whole code will execute faster), whereas in the first example if predicateA is true, predicateB will still always be evaluated, and you may also get some unexpected suprises if predicateA and predicateB are not mutually exclusive.

    0 讨论(0)
  • 2020-12-29 23:11

    else if would be faster in the sense that you compare until you hit a condition that resolves to true, and you skip the rest of the ifs.

    Also consider reordering the compares in order of descending frequency.

    And using the switch statement depending on the datatype of the object you are comparing.

    However at this point, as duffymo has suggested, you would be micro optimizing. The performance gain will never be as significant if you haven't chosen the right sorting algorithm for the job first.

    0 讨论(0)
  • 2020-12-29 23:12

    I doubt that a micro optimization like this will make a measurable difference in your code.

    Your sorting algorithm is more likely to be the source of a performance problem. Which sorting algorithm you choose will be critical, not many "ifs" versus "else if".

    UPDATE:

    The points made by others about "else if" being a better choice, due to its early exit and exclusive logic characteristics, suggest that it should be preferred over "if" in this case.

    But the point about algorithm choice still stands - unless your data set is very small.

    It's obvious that O(log n) would be better than O(n^2), but size of dataset matters as well. If you have only a few elements, you might not notice the difference. In that case, coding an inefficient method in the cleanest, most readable, most easily understandable at a glance could be your best bet.

    0 讨论(0)
  • 2020-12-29 23:12

    If the values are integers you may achieve an optimisation by using a table lookup. E.g. say you have 256 values that map into 7 days somehow, you could set up an array with 256 cells and each cell contained the day of week you wanted. Then instead of:

    
    if ( value == 0 ) {
      dayofweek = 1;
    } else if ( value == 1 ) {
      dayofweek = 2;
    } else if ( value == 2 ) {
      dayofweek = 3;
    } else if ...
    

    .. you could have..

    
    dayofweek = lookuparray[value];
    

    Of course, if you use this technique, then you should check the bounds of value first.

    0 讨论(0)
提交回复
热议问题