What is faster: many ifs, or else if?

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

    In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.

    The fastest would be a table dispatch, which is what a switch statement gets optimized into when there are enough cases in it (if there are few cases in a switch, it gets translated into a series of if-else checks in the resulting machine code).

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

    I would put another vote in for opting for a switch() statement instead.

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

    You can have a look at phpbench

    But to be honest if you want to optimize at this level, you might want to learn something else than php.

    alt text

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

    The decision to use many if-statements or one if-elseif-elseif... should not rely on performance, since this decision involves the program flow massively.

    I doubt that you can switch from many if-statements to a big if-elseif without loosing functionality.

    Its a design question, not a perfomance one.

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

    I made a benchmark if there's a true difference between successive if() and if() then a few elseif()

    I put a big string and did about 20 strpos() each time (x100 000) with the two methods and it showed this result :

    Try 1 : 0.5094 (including elseif)
    Try 2 : 0.6700 (including only if)
    

    There's no doubt. I already knew sucessive elseif() were faster, even though there's a return in the middle ; it's still good to put some statistics in the answer.

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