What is the difference between Switch and IF?

前端 未结 5 548
终归单人心
终归单人心 2021-01-13 10:30

I know this may be simple question but want to know every ones opinion on this.

what is the difference between switch and IF function in PHP?? What I can see is wher

5条回答
  •  余生分开走
    2021-01-13 10:47

    Or any performance wise difference between two??

    Forget about the performance difference on this level- there may be a microscopic one, but you'll feel it only when doing hundreds of thousands of operations, if at all. switch is a construct for better code readability and maintainability:

    switch ($value) 
     {
     case 1:   .... break;
     case 2:   .... break;
     case 3:   .... break;
     case 4:   .... break;
     case 5:   .... break;
     default:  .... break;
     }
    

    is mostly much more clean and readable than

    if ($value == 1) { .... }
    elseif ($value == 2) { .... }
    elseif ($value == 3) { .... }
    elseif ($value == 4) { .... }
    elseif ($value == 5) { .... }
    else { .... }
    

    Edit: Inspired by Kuchen's comment, for completeness' sake some benchmarks (results will vary, it's a live one). Keep in mind that these are tests that run 1,000 times. The difference for a couple of if's is totally negligeable.

    • if and elseif (using ==) 174 µs
    • if, elseif and else (using ==) 223 µs
    • if, elseif and else (using ===) 130 µs
    • switch / case 183 µs
    • switch / case / default 215 µs

    Conclusion (from phpbench.com):

    Using a switch/case or if/elseif is almost the same. Note that the test is unsing === (is exactly equal to) and is slightly faster then using == (is equal to).

提交回复
热议问题