Switch vs if statements

22,396

Solution 1

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 )

Solution 2

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.

Solution 3

The switch statement will be faster because it only checks the value once.

Solution 4

First what you have is not the same

switch(value)
  case condition1:
    break;
  case condition2:
    break

if (condition1) {
}
if (condition2) {
}

These are synonymous

switch(value)
  case condition1:
    break;
  case condition2:
    break

if (condition1) {
}
else if (condition2) {
}

Second if you are talking about my second example where the two are synonymous. Then using switch statements can ease some pain in coding lots of if ..else if statements....

Switches in my point of view can also provide a bit more readability. But even then there are times when using if...else is simply better especially with complex logic.

Solution 5

If you have a single variable, a set of possible values, and you want to perform different actions for each value, that's what switch-case is for.

Switch statements make it more obvious that you are merely determining which of the allowed values a variable had.

If you have more complex conditions, or multiple variables to consider, use if-statements.

Share:
22,396
CyberJunkie
Author by

CyberJunkie

Updated on July 09, 2022

Comments

  • CyberJunkie
    CyberJunkie almost 2 years

    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
    }  
    
  • CyberJunkie
    CyberJunkie over 13 years
    You make a good point especially with my broad example! For this I vote your answer correct :)
  • Anonymous Penguin
    Anonymous Penguin almost 10 years
    +1 for there are time when using if... else is simply better... I find myself always using if statements with booleans as it provides easier flow.