该线程有点旧,但我做了一些与该问题相关的测试,所以我不妨发布它:
测试代码(PHP 5.3.3 - CentOS 版本 6.5(最终版)):
class NonExistant
{
protected $associativeArray = array(
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four',
'five' => 'five',
'six' => 'six',
);
protected $numIterations = 10000;
public function noCheckingTest()
{
for ($i = 0; $i < $this->numIterations; $i++) {
$this->associativeArray['none'];
}
}
public function emptyTest()
{
for ($i = 0; $i < $this->numIterations; $i++) {
empty($this->associativeArray['none']);
}
}
public function isnullTest()
{
for ($i = 0; $i < $this->numIterations; $i++) {
is_null($this->associativeArray['none']);
}
}
public function issetTest()
{
for ($i = 0; $i < $this->numIterations; $i++) {
isset($this->associativeArray['none']);
}
}
public function arrayKeyExistsTest()
{
for ($i = 0; $i < $this->numIterations; $i++) {
array_key_exists('none', $this->associativeArray);
}
}
}
结果是:
| Method Name | Run time | Difference
=========================================================================================
| NonExistant::noCheckingTest() | 0.86004090309143 | +18491.315775911%
| NonExistant::emptyTest() | 0.0046701431274414 | +0.95346080503016%
| NonExistant::isnullTest() | 0.88424181938171 | +19014.461681183%
| NonExistant::issetTest() | 0.0046260356903076 | Fastest
| NonExistant::arrayKeyExistsTest() | 1.9001779556274 | +209.73055713%
所有函数的调用方式都与via相同call_user_func()
并定时与microtime(true)
观察结果
empty()
and isset()
明显优于其他两种方法,这两种方法与性能几乎紧密相关。
is_null()
表现不佳,因为它需要首先查找值,与访问不存在的值几乎相同$this->associativeArray['none']
,这涉及到数组的完整查找。
然而,我对它的表现感到惊讶array_key_exists()
。其速度慢 2 倍empty()
and isset()
.
NOTE:
我测试过的所有函数都有不同的用途,这个基准仅适用于您想要快速检查数组中的值的最通用用例。我们可以讨论是否null
应该被视为一个“值”或只是不存在的指标,但这是另一个话题。 o.o
更新2017-01-20
使用 PHP 7.1
修复了@bstoney 提到的错误
$ php -v
PHP 7.1.0 (cli) (built: Dec 2 2016 03:30:24) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.1.0-dev, Copyright (c) 1998-2016 Zend Technologies
$ php -a
php > $a = ['one' => 1, 'two' => 2, 'three' => 3];
php > $numIterations = 1000000;
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { $a['none']; }; echo microtime(true) - $start;
0.43768811225891
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { empty($a['none']); }; echo microtime(true) - $start;
0.033049821853638
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { is_null($a['none']); }; echo microtime(true) - $start;
0.43995404243469
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { isset($a['none']); }; echo microtime(true) - $start;
0.027907848358154
php > $start = microtime(true); for ($i = 0; $i < $numIterations; $i++) { array_key_exists('none', $a); }; echo microtime(true) - $start;
0.049405097961426