I have this code:
$worked = null;
unset($worked);
$mem = memory_get_usage();
$worked = $worker -> work($a, $b);
print_r($worked);
echo 'MEM: '.(memory_get_usage() - $mem), PHP_EOL;
Neither $a
nor $b
is passed by reference.
Which outputs:
Array
(
[aa] => Array
(
[11] => 0
[22] => 0
[33] => 18
)
[bb] => Array
(
[11] => 0
[22] => 0
[33] => 18
)
[cc] => Array
(
[11] => 0
[22] => 0
[33] => 81
)
[dd] => Array
(
[11] => 0
[22] => 0
[33] => 81
)
)
MEM: 222288
Variable $worked
is just a small array that shouldn't take up 222KB at all. It seems memory used by the execution of $worker -> work()
method is not freed up?
Why? I thought returning from a function would destroy everything inside?
The above code is in a loop with thousands of executions per PHP run and it keeps piling up the memory usage and not freeing it up at all hurling towards an out of memory fatal error.
How can I force it free up the memory after returning from the method?
The prove that the memory is piling up is not done by your code. Try it like this and please report the result:
$worked = null;
$worked = $worker -> work($a, $b);
$mem = memory_get_usage();
print_r($worked);
unset($worked);
echo 'MEM 1: '.$mem, PHP_EOL;
echo 'MEM 2: '.memory_get_usage(), PHP_EOL;