Switch vs if statements(切换与 if 语句)
问题描述
我进退两难了.哪个最好用,为什么.. switch 或 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
两次.
The second will test $x
twice.
您可能希望将第二个 if
设为 else if
.这意味着一旦一个条件评估为 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 )
这篇关于切换与 if 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:切换与 if 语句


基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01