Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are PHP Closure Objects eligible for garbage collection

I was wondering if anyone knows if PHP's anonymous functions are eligible for garbage collection?

I know that functions created with create_function are not garbage collected but I haven't been able to find any reference about ones created with the function(){} syntax (internally represented as a Closure object).

like image 940
Orangepill Avatar asked Dec 26 '22 03:12

Orangepill


1 Answers

PHP's garbage collector does not discriminate between types of "things" - if it has at least one reference somewhere, it is kept. The moment this does not apply, the resource is garbage-collected.

This is not the same as using create_function, as PHP throws the create_function reference in the global scope in addition to referencing it. A closure (a Closure object, if you prefer, as this is what they are!) only exists in the scope it was created in + all the ones you pass it to.

If you want to convince yourself of it, run this little piece of code:

<?php
$r = memory_get_usage();
for ($i = 0; $i < 100; $i++) {
    $k = function() {echo "boo"; };
    if (memory_get_usage() > $r) {
            echo "Different memory count. Off by: ".(memory_get_usage() -$r);
    }
    $r = memory_get_usage();
}

You will get exactly one echo. Replace the $k assignment with create_function, and you'll get 100.

like image 146
Sébastien Renauld Avatar answered Jan 05 '23 00:01

Sébastien Renauld