What is faster: many ifs, or else if?

后端 未结 11 1845
夕颜
夕颜 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: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.

提交回复
热议问题