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

前端 未结 7 1666
遥遥无期
遥遥无期 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条回答
  •  猫巷女王i
    2020-12-05 18:10

    You probably won’t notice any difference in performance for such a limited number of expressions. But theoretically, the if..if..if requires to check every single expression. If single expressions are mutally exclusive, you can save that evaluation by using if..else if.. instead. That way only when the previous cases fail, the other expression is checked.

    Note that when just checking an int for equality, you could also just use the switch statement. That way you can still maintain some level of readability for a long sequence of checks.

    switch ( p )
    {
        case 0:
            do_this();
            break;
    
        case 1:
            do_that();
            break;
    
        case 2:
            do_these():
            break;
    }
    

提交回复
热议问题