首先我找到了这个object vs array,然后在代码中添加了一个ArrayObject并扩展了ArrayObject。结果是奇怪的:在计算时间方面,扩展的ArrayObject接近于普通的ArrayObject。
这是我的测试用例,数组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快?
发布于 2014-01-01 21:48:52
这是因为使用扩展数组对象的函数不是设置$z‘It’2000次,而是使用ArrayObject设置。
如果我添加了一个扩展数组对象函数的版本,它确实设置了$z‘a’,则结果更加一致:
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 (no aaa)');
/* added MyArray function with $z['aaa'] = 'aaa' added to the loop */
profiling(function()
{
global $times;
for ($i=0; $i<$times; $i++) {
$z = new MyArray();
for ($j=0; $j<$times; $j++) {
$z['aaa'] = 'aaa';
$z['bbb'] = 'bbb';
$z['ccc'] = $z['aaa'].$z['bbb'];
}
}
}, 'use extends arrayobject (with aaa)');产出如下:
use array: 1.3838648796082
use object: 1.9023339748383
use arrayobject: 2.0339980125427
use extends arrayobject (no aaa): 1.6399688720703
use extends arrayobject (with aaa): 2.040415763855
phpversion 5.4.4-14+deb7u7注意,使用ArrayObject的函数和循环中使用$z‘’aaa的扩展ArrayObject的函数有更近的时间。
https://stackoverflow.com/questions/20837789
复制相似问题