Here is the code to check:
<?php function testnochanges($arr1){ foreach($arr1 as $val){ // } return $arr1; } function testwithchanges($arr1){ $arr1[] = 1; return $arr1; } echo "Stage 0: Mem usage is: " . memory_get_usage() . "<br />"; for ($i = 0; $i < 100000; ++$i) { $arr[] = rand(); } echo "Stage 1 (Array Created): Mem usage is: " . memory_get_usage() . "<br />"; $arrtest1 = testnochanges($arr); echo "Stage 2 (Function did NO changes to array): Mem usage is: " . memory_get_usage() . "<br />"; $arrtest2 = testwithchanges($arr); echo "Stage 3 (Function DID changes to array): Mem usage is: " . memory_get_usage() . "<br />"; ?>
and here is the result after launch:
Stage 0: Mem usage is: 330656 Stage 1 (Array Created): Mem usage is: 8855296 Stage 2 (Function did NO changes to array): Mem usage is: 8855352 Stage 3 (Function DID changes to array): Mem usage is: 14179864
At stage 0, we see that before creating the array, PHP already uses some space in memory. After creating the first array ( Stage 1 ), we can see big changes in memory usage, as expected. But after calling the testnochanges function and creating $arrtest1 in Stage 2, we see that the memory usage has not changed much. This is because we did not make changes to $arr , so $arrtest1 and $arr still point to the same array. But in Stage 3 , where we call the testwithchanges function and add the element to $arr PHP performs copy-on-write , and the returned array, which is assigned to $arrtest2 , now uses a different part of memory and again we see a big increase in memory usage.
Dry conclusion: if you copy an array to another array and do not change it, the memory usage remains the same as both arrays are pointed to the same. If you change the array, then PHP does copy-on-write and, of course, memory usage is increasing.
Good to read: Be careful with garbage collection, part 2 .
F0g
source share