PHP:切换vs if [英] PHP: switch vs if

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

问题描述

哪种形式更有效

这一种:

switch($var) {
  case 1:

    break;
  case 2:

    break;
}

..或者这一个:

if( $var === 1 ) {

} elseif( $var === 2 ) {

}

就性能而言?

推荐答案

表现方面完全不相关。

作为 PHPBench 显示,即使有1,000次操作,两者之间的差异大约为188微秒,即188 <百万分之一秒。 PHP代码通常有更大的瓶颈:单个数据库调用通常需要几十毫秒,这是数万倍。

As PHPBench shows, even with 1,000 operations, the difference between the two is about 188 microseconds, that's 188 millionths of a second. PHP code usually has much bigger bottlenecks: a single database call will often take tens of milliseconds, that's tens of thousands of times more.

使用您喜欢的代码,以及代码的可读性更好的代码 - 对于许多支票,很可能是开关

Use whichever you like, and whichever is better for your code's readability - for many checks, most likely the switch.

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

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