public function foo($file1, $file2){
$obj = new Obj();
$data = array();
$data[] = $obj->importAFile($file1);
$data[] = $obj->importAFile($file2);
return $data;
}
Does the memory allocated for $obj get freed after the return?
If not how can I free it?
unset() does not force immediate memory freeing, and it is used to free variable usage. PHP garbage collector cleans up the unset variables.
The 'memory_limit' is the maximum amount of server memory that a single PHP script is allowed to use. The value needs to be converted before comparing the threshold of memory. For example − 64M is converted to 64 * 1024 * 1024. After this, the comparison is done and the result is printed out.
PHP memory management functions are invoked by the MySQL Native Driver through a lightweight wrapper. Among others, the wrapper makes debugging easier. The various MySQL Server and the various client APIs differentiate between buffered and unbuffered result sets.
The memory_get_usage function can be used to track the memory usage. The 'malloc' function is not used for every block required, instead a big chunk of system memory is allocated and the environment variable is changed and managed internally.
By using unset() on a variable, you've marked it for 'garbage collection' literally, as PHP doesn't really have one, so the memory isn't immediately available. The variable no longer houses the data, but the stack remains at the current size even after calling unset(). Setting the variable to NULL drops the data and shrinks the stack memory almost immediately.
This has worked for me on several occasions where memory exhausted warnings were thrown before the tuning, then calling unset() after nullifying the variable. Calling unset after nullifying mightn't be necessary but I used it nonetheless after the nullification.
PHP uses garbace collector. It frees all variables to which there are no references left. Assuming that $obj->importAFile() does not return reference to $obj, the memory will be freed. However, there is no guarantee when the memory will be freed. If $obj contains reference to itself, in older versions of PHP the memory won't be freed as well. You can read more in PHP documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With