What is faster: many ifs, or else if?

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

提交回复
热议问题