I have an array of size 5 MB, I am passing it to functions to functions (I am not passing it by reference)
foo( $arr );
function foo( $arr ) {
....
bar( $arr );
....
}
function bar( $arr ) {
....
test( $arr );
....
}
function test( $arr ) {
....
test2( $arr );
....
}
PHP passes array values by value (copy of value) by default to functions.
my question is, if this array value is passed to 100 functions calls, will the PHP consumes 100 x 5 MB = 500 MB of memory ?
How the PHP handles big arrays ( in memory wise ) on function calls?
Here is a code to test:
and here is a output after i run it:
On stage 0 we can see that before array is created PHP is already using some space in memory. After creating first array (Stage 1) we can see a big change in memory usage as expected. But after calling function
testnochangesfunction and creating$arrtest1on Stage 2, we see that memory usage did not change a lot. It’s because we did no changes to$arr, so$arrtest1and$arrstill are pointing to the same array. But on Stage 3, where we calltestwithchangesfunction, and add an element to$arrPHP performscopy-on-writeand returned array which is assigned to$arrtest2now uses different part of memory and again we see a big grow of memory usage.Dry conclusion: If you copy array to another array and do not change it, memory usage stays the same as both arrays are pointed to the same one. If you change the array PHP performs
copy-on-writeand, of course memory usage grows.Good thing to read: Be wary of garbage collection, part 2.