[PHP-DEV] Copy on write  
Author Message
dletz





PostPosted: 2007-4-23 23:04:04 Top

php-dev, [PHP-DEV] Copy on write Hello everyone

in version the 5.2.1 i get strange results when using the reference =

operator on arrays. When writing a function "a" with call by reference:
function &a(&$anArray) { return $anArray; }
and another function "b":
function b($anArray) { return $anArray; }

Then on my machine it takes much longer to call function "a" than to cal=
l =

function "b". Actually it seems that function "a" always copies the hole=
=

array wheter or not i write to it - while function "b" does not copy tha=
t =

array as long as i only read from it.
But why does function "a" copy at all? Has anyone a explanation?
Here is the benchmark code which shows the speed difference:

<?php
echo phpversion()."\n";
echo "test1\ttest2\n";
function a($p){return $p;}
function &b(&$p){return $p;}

$test1 =3D $test2 =3D array();
for ($i =3D 0;$i < 10000;$i++) {$test_array[] =3D $i;}
$repeat =3D 10;
for($j=3D0;$j<$repeat;$j++)
{
$start_time =3D microtime(true);
for ($i=3D0;$i<500;$i++) {
$x =3D a($test_array);
$x[0];
}

$execution_time =3D microtime(true) - $start_time;
echo number_format($execution_time,4)."\t";
$test1[] =3D $execution_time;

$start_time =3D microtime(true);
$count =3D count($test_array);
for ($i=3D0;$i<500;$i++) {
$x =3D b($test_array);
$x[0];
}

$execution_time =3D microtime(true) - $start_time;
echo number_format($execution_time,4)."\n";
$test2[] =3D $execution_time;
}
echo "=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D\n";
echo number_format(array_sum($test1)/$repeat,4)."\t";
echo number_format(array_sum($test2)/$repeat,4)."\n";

?>

Output on my machine:
5.2.1
test1 test2
0.0004 0.8020
0.0004 0.7862
0.0004 0.7970
0.0004 0.7752
0.0004 0.7783
0.0004 0.7797
0.0004 0.7834
0.0004 0.7806
0.0004 0.7747
0.0004 0.7777
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
0.0004 0.7835

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php