# Copy on write

- Thread: https://externals.io/message/28956
- Original archive: https://news-web.php.net/php.internals/28956
- Started by dletz@blog.de on 2007-04-23T14:58:59+00:00
- Messages: 1
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #28956 — dletz@blog.de — 2007-04-23T14:58:59+00:00

URL: https://externals.io/message/28956#28956

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 call  
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 that  
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 = $test2 = array();
for ($i = 0;$i < 10000;$i++) {$test_array[] = $i;}
$repeat = 10;
for($j=0;$j<$repeat;$j++)
{
     $start_time = microtime(true);
     for ($i=0;$i<500;$i++) {
         $x = a($test_array);
         $x[0];
     }

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

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

     $execution_time = microtime(true) - $start_time;
     echo number_format($execution_time,4)."\n";
     $test2[] = $execution_time;
}
echo "==============\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
==============
0.0004	0.7835
