切换vs if语句 [英] Switch vs if statements

查看:102
本文介绍了切换vs if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处于两难境地。哪个最好用,为什么..切换或如果?

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
}  


推荐答案

它们有不同的含义。

第一个例子将在满足条件时停止。

The first example will stop when the condition is met.

第二个将测试 $ x 两次。

你可能想要第二个,如果一个,如果。这意味着只要一个条件评估为 true ,就会跳过该块。

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.

过早优化......(你知道其余的:P)

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

这篇关于切换vs if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆