在 php 中运行布尔检查或只是简单的 == 1 / == 0 更快
在 php 中检查布尔值(如
if($var)
or
if($var == 1)
和
if(!$var)
or
if($var == 1)
var 只能是 1 或 0)是否更快?
Is it faster in php to check for a boolean value like,
if($var)
or
if($var == 1)
and
if(!$var)
or
if($var == 1)
var
can only be 1 or 0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我预计直接评估变量的真实性会比测试两个变量是否相等更快。我的测试表明情况确实如此。您会期望在评估 == 运算符时存在更高级别的间接寻址(它是对返回真值的附加函数的调用?),因此它会增加一些非常小的开销。
有些人认为这是不成熟的微观优化。我个人不认为这是因为
我个人更喜欢阅读
if ($var) {}
而不是if ($var == 1) {}
< /p>这只需要非常基本的理解语言知道任何真实(相当于真实)值可以在 if 语句内求值
在某些方面,它可能会提高人们对if 语句如何工作(任何阻止
if ($var == true) {}
if 仅一小部分的内容肯定是有帮助的)鉴于它也更快,这些点似乎表明
if ($var) {} 作为更好的选择。至少在考虑到我的个人喜好时,我是这么认为的。
I expected that directly assessing the truthy-ness of a variable would be quicker than testing if two variables are equal. My tests show this to be the case. You would expect there to be a higher level of indirection when the == operator is evaluated (it's a call to an additional function which returns a truth value?), and hence it adds some very tiny overhead.
Some people have suggested this is a premature micro-optimisation. I personally don't think it is because
Personally I prefer to read
if ($var) {}
thanif ($var == 1) {}
It only takes a very basic understanding of the language to know that any truthy (equivalent to true) value can be evaluated inside the if statement
In some ways it might raise awareness of how the if statement works (anything that discourages
if ($var == true) {}
if only by a fraction is surely helpful)Given that it is faster as well, it would seem that these points, albeit marginal, indicate
if ($var) {}
as the better option. At least that's how it seems to me when factoring in my personal preferences.if($var) 更快。您可以查看此链接 http://hbfs。 wordpress.com/2008/08/26/optimizing-boolean-expressions-for-speed/ 了解更多详细说明。
if($var) is faster. You can check this link out http://hbfs.wordpress.com/2008/08/26/optimizing-boolean-expressions-for-speed/ for more detail explanation.
查看此网站:
http://www.phpbench.com/
Check this site out:
http://www.phpbench.com/