首先我找到了这个对象 vs 数组,然后我在我的代码中添加了一个 ArrayObject 和扩展的 ArrayObject 。结果很奇怪:扩展的 ArrayObject 在计算时间上接近普通的 ArrayObject。
这是我的测试用例,数组 vs 对象 vs 数组对象 vs 扩展数组对象:
<pre><?
set_time_limit(0);
$times = 2000;
function profiling($tester, $desc)
{
$start = microtime(true);
$tester();
echo "$desc: ",(microtime(true) - $start),"\n";
}
profiling(function()
{
global $times;
for ($i=0; $i<$times; $i++) {
$z = array();
for ($j=0; $j<$times; $j++) {
$z['aaa'] = 'aaa';
$z['bbb'] = 'bbb';
$z['ccc'] = $z['aaa'].$z['bbb'];
}
}
}, 'use array');
profiling(function()
{
global $times;
for ($i=0; $i<$times; $i++) {
$z = (object) null;
for ($j=0; $j<$times; $j++) {
$z->aaa = 'aaa';
$z->bbb = 'bbb';
$z->ccc = $z->aaa.$z->bbb;
}
}
}, 'use object');
profiling(function()
{
global $times;
for ($i=0; $i<$times; $i++) {
$z = new ArrayObject();
for ($j=0; $j<$times; $j++) {
$z['aaa'] = 'aaa';
$z['bbb'] = 'bbb';
$z['ccc'] = $z['aaa'].$z['bbb'];
}
}
}, 'use arrayobject');
profiling(function()
{
global $times;
for ($i=0; $i<$times; $i++) {
$z = new MyArray();
for ($j=0; $j<$times; $j++) {
$z['bbb'] = 'bbb';
$z['ccc'] = $z['aaa'].$z['bbb'];
}
}
}, 'use extends arrayobject');
class MyArray extends ArrayObject
{
function __construct()
{
parent::__construct(array('aaa'=>'aaa'));
}
}
echo 'phpversion '.phpversion();
在我的电脑上,输出是
use array: 4.1052348613739
use object: 5.6103208065033
use arrayobject: 5.4503121376038
use extends arrayobject: 4.5252590179443
phpversion 5.3.25
排名为:数组 > 扩展数组对象 > 数组对象 > 对象。
为什么extends ArrayObject
比 ArrayObject 和 Object 快?