应该使用 if ($a != NULL) 还是 if ($a !== NULL) 来控制程序流程?
这可能是一个令人痛苦的基本问题,但我想知道使用 PHP 的 if equal !==
与 if equal 的性能问题!=
控制流程。
考虑以下简单的 PHP 函数:
<?php
function test_json($json = NULL) {
if ($json != NULL) {
echo 'You passed some JSON.';
} else {
echo 'You failed to pass any JSON.';
}
}
?>
从性能的角度来看,是否最好使用 如果相同 (!==
) 来防止 PHP 迭代变量类型,试图找到一个有效的比较?
我假设 !==
首先比较变量类型,如果失败,它会立即返回FALSE
? 从 PHP3 开始我几乎就本能地使用了 !=
。现在我正在从事一些计算密集型项目,微小的性能考虑变得更加令人担忧。
当然,欢迎对流量控制优化提出其他意见!
This is perhaps a painfully basic question to answer, but I'm wondering about performance issues regarding using PHP's if identical !==
versus if equal !=
to control flow.
Consider the following trivial PHP function:
<?php
function test_json($json = NULL) {
if ($json != NULL) {
echo 'You passed some JSON.';
} else {
echo 'You failed to pass any JSON.';
}
}
?>
From a performance standpoint, is it preferable to employ if identical (!==
) to prevent PHP iterating through variable types, attempting to find a valid comparison?
I assume that !==
first compares the variable types, and if that fails, it immediately returns FALSE
?
I've used !=
since PHP3 almost as a reflex. Now that I'm working on some much more computationally-intensive projects, minute performance considerations become more of a concern.
Other comments on flow control optimization are, of course, welcome!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我还没有对松散与严格比较运算符进行任何性能测试,但对于您想要做的事情,我建议您
在 http://www.php.net/manual/en/function.is-null.php
编辑:我链接的 php 页面注释中的注释上面的一些结果表明
===
运算符比==
运算符稍快,两者都比is_null()
快>。然而,另一条注释指出“ ===NULL 和 is_null 之间的执行时间差异小于 250 纳秒。去优化重要的东西。”我不得不同意这一点。综上所述,我建议您选择您认为最具可读性的内容。I haven't done any performance tests on loose vs strict comparison operators, but for what you are trying to do, I would instead recommend something like
More information on
is_null()
at http://www.php.net/manual/en/function.is-null.phpEDIT: a note in the comments of the php page I linked to above has some results showing that the
===
operator is slightly faster than the==
operator, both of which are faster thanis_null()
. However, another note points out that "The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters." I'd have to agree there. So all that said, I would suggest you go with what you deem to be the most readable.你可以在询问之前编写这样的测试代码;根据测试“使用“===”比 is_null() 快 30 倍。
http://www.php.net/manual/en/language .types.null.php#77937
You could write a test code like this before asking; according to test "Using "===" is 30x quicker than is_null()."
http://www.php.net/manual/en/language.types.null.php#77937