Do not use is_null()

测试一个变量是否为 NULL,我曾喜欢用 is_null() 函数,现在发现还比如直接用 === 比较来得快。

php.net 上有人写了个测试,得出的结论是 === 比 is_null() 快30倍。


$v = NULL;

$s = microtime(TRUE);
for($i=0; $i<1000; $i++) {
    is_null($v);
}
print microtime(TRUE)-$s;
print "<br>";

$s = microtime(TRUE);
for($i=0; $i<1000; $i++) {
    $v===NULL;
}
print microtime(TRUE)-$s;

这是2007年的事情了,我不清楚他的环境配置。如今在我 Intel(R) Celeron(R) CPU 2.80GHz PC 充当的测试服务器上,running zend server php 5.2.9,得出的结论是 === 比 is_null() 快1-2倍。看来 php is_null() 的效率进步了不少,但还是慢。以后我得改用 NULL === $v 的方式了。

Leave a comment

Your email address will not be published. Required fields are marked *