Last Updated: February 25, 2016
·
664
· mauris

Scope variables for better GC in JS and PHP

You can write self-executing functions in JS and PHP (Closures in PHP 5.3 or higher) to scope your variables for better memory and GC management.

JS and PHP allows declaration of variables globally and hence if a variable is declared global, the GC of that variable will only be done at the end of execution - not effective.

Put these variables into smaller scopes. If needed, write self-executing functions to help manage these variables better:

PHP

call_user_func(function(){
    $var = resource_intensive_func();
});

JavaScript

(function(){
    var data = data();
})();