First I found this object vs array, then I added an ArrayObject and extended ArrayObject to my code. The result is strange: The extended ArrayObject is close to the common ArrayObject in terms of computing time.
This is my test case, array vs object vs arrayobject vs extended arrayobject:
<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();
On my pc, the output is
use array: 4.1052348613739
use object: 5.6103208065033
use arrayobject: 5.4503121376038
use extends arrayobject: 4.5252590179443
phpversion 5.3.25
The ranking is: array > extends arrayobject > arrayobject > object.
Why is the extends ArrayObject
faster than ArrayObject and Object?
It is because your function using the extended array object is not setting $z['aaa'] 2000 times but your function using ArrayObject is.
if i add a version of the extended array object function which does set $z['aaa'] the result is more consistant:
output is as follows:
notice that the function using ArrayObject and the function using the extended ArrayObject with $z['aaa'] in the loop have much closer times.