As my understanding , when i passed array by value , a copy of array is created. i.e in below program $y & $z should need same memory as of $x. however memory utilization hardly increases. Obviousy my understanding is wrong , Can anyone explain the reason.
for($i=0;$i<1000000;$i++)
$x[] = $i; // memory usage : 76519792
echo memory_get_usage();
function abc($y){
$y[1] = 1; //memory usage : 76519948
$z[]= $y; //memory usage : 76520308
}
I heard that php uses copy-on-write: http://en.wikipedia.org/wiki/Copy-on-write
as an example:
<?
for($i=0;$i<100000;$i++)
$x[] = $i;
// we output the memory use:
echo memory_get_usage().'<br/>'; // outputs 14521040
// here we equate $y to $x, but instead of creating a copy,
// php engine just creates a pointer to the same memory space
$y = $x;
echo memory_get_usage().'<br/>'; // outputs 14521128
// here we change something in y, now php engine
// "creates a seperate copy" for y and makes the change
$y[1]=8;
echo memory_get_usage().'<br/>'; // outputs 23569904
?>
and similar behaviour with the function calls:
<?
for($i=0;$i<100000;$i++)
$x[] = $i;
echo memory_get_usage().'<br/>'; /* 14524968 */
function abc($y){
echo memory_get_usage().'<br/>'; /* 14524968 */
$y[1] = 1;
echo memory_get_usage().'<br/>'; /* 23573752 */
$z[]= $y;
echo memory_get_usage().'<br/>'; /* 23574040 */
}
abc($x);
echo memory_get_usage().'<br/>'; /* 14524968 */
?>
PS: I am testing this on windows, maybe it is different on linux
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With