On Mon, 11 Feb 2008 16:03:25 +0100, Xu, Qian <no_reply@microsoft.com
wrote:
Quote:
Hi All,
>
is there a Copy-on-Write semantic behind PHP compiler?
>
$a = long_string_1mb;
$b = $a; // Compiler will allocates another 1MB for this variable.
Not yet...
Quote:
I have to use "$b =& $a;" to avoid memory waste.
I think this should be done by compiler itself. For instance:
It is done. Only if you change either $a or $b will they be copied/doubled
(see memory usage on a test run here as a comment after the line):
<?php
echo memory_get_usage()."\n"; //55736
$a = str_repeat('a',1024*1024);
echo memory_get_usage()."\n"; //1104672
$b = $a;
//memory usage should be altered only slightly:
echo memory_get_usage()."\n";//1104696
$b = str_replace('foo','bar',$b);//
echo memory_get_usage()."\n";//2153344
unset($b);
echo memory_get_usage()."\n";//1104400
?>
Compared to reference (which will alter BOTH $a & $b):
<?php
echo memory_get_usage()."\n"; //55520
$a = str_repeat('a',1024*1024);
echo memory_get_usage()."\n"; //1104288
$b = &$a;
//memory usage should be altered only slightly:
echo memory_get_usage()."\n";//1104336
$b = str_replace('foo','bar',$b);//
echo memory_get_usage()."\n";//1104400
unset($b);
echo memory_get_usage()."\n";//1104400
?>
In short, as the manual allready states, don't use references as a
premature optimizer. The interpreter is smart enough to do it. Only use
references if you need the reference in your code.
--
Rik Wasmus