Performance difference of “if if” vs “if else if”

前端 未结 7 1636
遥遥无期
遥遥无期 2020-12-05 17:25

I was just thinking is there any performance difference between the 2 statements in C/C++:

Case 1:

if (p==0)
   do_this();
else if (p==1)
   do_that(         


        
相关标签:
7条回答
  • 2020-12-05 18:24

    The major difference is that the if/else construct will stop evaluating the ifs() once one of them returns a true. That means it MAY only execute 1 or 2 of the ifs before bailing. The other version will check all 3 ifs, regardless of the outcome of the others.

    So.... if/else has a operational cost of "Up to 3 checks". The if/if/if version has an operational cost of "always does 3 checks". Assuming all 3 of the values being checked are equally likely, the if/else version will have an average of 1.5 ifs performed, while the if/if one will always do 3 ifs. In the long term, you're saving yourself 1.5 ifs worth of CPU time with the "else" construct.

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