Last Updated: February 25, 2016
·
1.091K
· 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();
})();

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside