Php is passed by value or by reference

As I understand it, when I passed an array by value, a copy of the array is created. that is, in the below software $ y and $ z, the same memory is required as for $ x. however, memory usage is practically not increasing. Obviously, my understanding is wrong, can someone 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

}
+5
source share
1 answer

I heard php use 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 behavior with 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 from linux

+3
source

All Articles