Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch vs if statements

I'm in a dilemma. Which is best to use and why.. switch or if?

switch ($x) 
{
case 1:
  //mysql query 
  //echo something
  break;
case 2:
  //mysql query 
  //echo something
  break;
}

...

if ($x == 1) {
    //mysql query 
    //echo something    
} 

if ($x == 2) {   
    //mysql query 
    //echo something
}  
like image 801
CyberJunkie Avatar asked Nov 22 '10 02:11

CyberJunkie


Video Answer


2 Answers

They have different meanings.

The first example will stop when the condition is met.

The second will test $x twice.

You may want to make your second if an else if. This will mean the block will be skipped as soon as one condition evaluates to true.

But if you are wondering which one is fastest, you should instead think which one most effectively communicates what I want to do. They will both most probably end up as conditional jumps in the target architecture.

Premature optimisation... (you know the rest :P )

like image 187
alex Avatar answered Sep 28 '22 11:09

alex


Switch is better when there are more than two choices. It's mostly for code readability and maintainability rather than performance.

As others have pointed out, your examples aren't equivalent, however.

like image 20
ddrace Avatar answered Sep 28 '22 09:09

ddrace