Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
}  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
347 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...