Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free memory in PHP?

Tags:

object

php

memory

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?

like image 801
Jane Avatar asked Aug 25 '11 11:08

Jane


People also ask

Does PHP unset clear memory?

unset() does not force immediate memory freeing, and it is used to free variable usage. PHP garbage collector cleans up the unset variables.

How can I limit my PHP memory?

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.

How does PHP manage memory?

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.

How do I monitor PHP memory usage?

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.


2 Answers

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.

like image 108
Babatunde Adeyemi Avatar answered Oct 04 '22 09:10

Babatunde Adeyemi


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

like image 29
Maxim Krizhanovsky Avatar answered Oct 04 '22 10:10

Maxim Krizhanovsky