| 
        php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
  [2005-06-27 11:31 UTC] robert dot munteanu at betbrain dot com
 Description:
------------
Whenever you create an object in a method, memory is not released when the method execution ends, unset() must be called manually.
This becomes a problem when you have long-running scripts, which perform actions repeatedly which leads to the script running out of memory.
Reproduce code:
---------------
<?php
class Tester {
    public function doNothing() {
        $res = array();
        for ( $i = 0; $i < 10000; $i++) {
            $res[$i] = new StdClass;
        }
    }
}
$t = new Tester();
echo "Before: ".memory_get_usage()."\n";
$t->doNothing();
echo "After: ".memory_get_usage()."\n";
?>
Expected result:
----------------
Memory usage remains roughly the same.
Actual result:
--------------
Before: 41424
After: 432560
PatchesPull Requests
Pull requests: 
HistoryAllCommentsChangesGit/SVN commits             
             | 
    |||||||||||||||||||||||||||||||||||||
            
                 
                Copyright © 2001-2025 The PHP GroupAll rights reserved.  | 
        Last updated: Tue Nov 04 04:00:01 2025 UTC | 
Note that the memory is freed inside php, just not yielded back to the operating system until execution ends. In this example, the memory is claimed as the function executes, then re-used when the function is run again (instead of using up twice as much memory): ---------- <?php function doNothing() { $res = array(); for ( $i = 0; $i < 20000; $i++) { $res[$i] = new StdClass; } } // Unix only function get_usage() { $my_pid = getmypid(); $usage = `ps -eo%mem,rss,pid | grep $my_pid`; $kb = preg_split("/\s+/", $usage); return sprintf("%.3f",$kb[2] / 1024) . "MB"; } echo "Before: ".get_usage()."\n"; doNothing(); echo "One Use: ".get_usage()."\n"; doNothing(); echo "Two Uses: ".get_usage()."\n"; ?> Output ------ Before: 5.555MB One Use: 10.164MB Two Uses: 10.293MB