Freeing memory with PHP



Introduction

           It is a good practice to free the memory of a variable after its usage so that the freed memory can utilize for some other processes ie by deallocating the space occupied by the user defined variables, giving back the memory utilized. In PHP there are two ways to free the memory.

                                      unset() or $var = null

          Unset() does unset a variable. It does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first.

         If you are doing $whatever = null; then you are rewriting variable's data. You might get memory freed / shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.
        
    <?php
         $ignore = array('GLOBALS', '_FILES', '_COOKIE', '_POST', '_GET', '_SERVER', '_ENV', 'argv', 'argc', 'ignore');
         $definedVariablesArr = array_diff_key(get_defined_vars() + array_flip($ignore), array_flip($ignore));
         foreach($definedVariablesArr AS $var) {
            ${$var} = NULL;
         }
         echo memory_get_usage();
    ?>


Get the full source code from GitHub.

Here we are initializing one array which contains all the built in variables in PHP so that we can filter out only the user defined variables. Diff the ignore list as keys after merging any missing ones with the defined list. Re-initialize all variables  to NULL

Check memory_get_usage() before and after initializing the variables to NULL.




No comments:

Post a Comment

Technologies

1. Nodejs
  • Express
  • Loopback
  • SailsJs
2. Angular
  • 2
  • 4
  • 5
  • 8
3. JQuery
4. PHP
  • LAMP
  • Codeigniter
  • Lumen
5. Database
  • MySQL
  • PostgreSQL
  • MongoDB
6. Artificial Intelligence
  • IBM Watson API
7. Amazon
  • S3
  • EC2
  • SES
  • ELB
8. REST & SOAP API integrations
9. Push notifications
  • FCM - Android
  • APNS - IOS
10. RETS(Real estate domain) servers
11. Standard Implementations
  • 508
  • LTI