Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a PHP script constantly take up more memory?

Tags:

php

See this example:

echo memory_get_usage() . "\n"; // 36640
$a = str_repeat("Hello", 4242);
echo memory_get_usage() . "\n"; // 57960
unset($a);
echo memory_get_usage() . "\n"; // 36744

Can anyone explain why after un-setting the variable the memory usage does not return to 36640

like image 842
Chris Avatar asked Jul 28 '26 22:07

Chris


2 Answers

If you do it twice the memory will stay at 36744...

echo memory_get_usage() . "\n"; // 36640
$a = str_repeat("Hello", 4242);
echo memory_get_usage() . "\n"; // 57960
unset($a);
echo memory_get_usage() . "\n"; // 36744
$a = str_repeat("Hello", 4242);
unset($a);
echo memory_get_usage() . "\n"; // -> 36744
like image 173
powtac Avatar answered Jul 30 '26 20:07

powtac


Garbage collection is an expensive operation, even if there's only a single variable to unset. PHP won't run the collector each time you unset a var, as that'd waste a huge amount of CPU time.

PHP will only run the collector when it has to, as in when something wants more memory than is available.

like image 23
Marc B Avatar answered Jul 30 '26 18:07

Marc B