Home  >  Article  >  Backend Development  >  php程序中 if(1==$user) 和 if($user ==1) 在效率上有区别吗?

php程序中 if(1==$user) 和 if($user ==1) 在效率上有区别吗?

WBOY
WBOYOriginal
2016-06-06 16:42:19981browse

两种写法都看到过

回复内容:

效率上没什么区别
--------------

if(1==$user)
在编程中,如果忘了一个=,程序会报错

if($user==1)
如果你忘了一个=,可能永远也发现不了

就是通过编程习惯来减少码代码时的错误,减少意外Bug 我来手动测试验证下:
<code class="language-text"><?php //test.php
$a = '1';
for($i=0;$i<=100000000;$i++){
    if(1 == $a){
        //
    }
}
</code></code>
追求性能到这种地步,你就换个语言吧! 在php这种动态语言中,比较这种效率问题得多蛋疼? 考虑这种情况的效率毫无意义 感谢邀请! 虽然没做过此类测试,但是感觉在效率上应该没啥差距。 欣赏楼主的这种态度。
<code class="language-text">$ time php test.php

real 0m12.352s
user 0m0.000s
sys 0m0.015s

$ time php test1.php

real 0m12.240s
user 0m0.000s
sys 0m0.031s

$ time php test2.php

real 0m4.635s
user 0m0.015s
sys 0m0.000s

$ time php test3.php

real 0m4.620s
user 0m0.000s
sys 0m0.015s
</code>
效率上很难看出区别。这种写法主要是为了避免把==写成=,毕竟头昏脑胀的时候一眼看上去$a = 1很像是对的,而1 = $a不管你怎么头昏脑胀还是会觉得不对。
此外这种习惯不仅存在于php的编写中,在其他语言里也很常见 这不涉及效率问题,这是一种代码习惯,以便于防止手误,将==写成=,这个错误是所有C及C衍生语言或类C语言程序员都犯过的错误~~
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn