If you are using larger files like bigger data files or images, memory might become an issue. Even if not, it's always good practice to use optimal amount of memory. Clearing memory is just a part of good programming techniques. This post/tutorial will try to go through related examples of the problem clear memory. You can't always rely on the GC (Garbage Collector).
Running out of memory
When you have been a PHP programmer for a while, I am sure you have run into fatal error when you have run out of memory.But be aware, it might mean that you have infinite loop somewhere.Source code viewer
PHP Fatal error: Allowed memory size of ... bytes exhausted (tried to allocate ... bytes) in ... on line ...Programming Language: Text
Current memory usage
memory_get_usage returns current memory usage in bytes. If you are using some kind of framework, it might have some function that converts it for you to KB or MB. Another useful function is memory_get_peak_usage, that way you can detect peaks. So usage is for optimization and peak is for debugging and finding weak spots.Source code viewer
Programming Language: PHP
Garbage Collection
Use unset to unset a variable or an object. PHPs garbage collector will remove it for real when it fits. The memory won't be forced to free itself to save CPU cycles. Do not set your variable or object to NULL, if you want to clear variable memory. If you do manually unset the variable, you can force memory freeing with gc_collect_cycles as of PHP 5.3, but it is not needed in normal circumstances.From PHP 5.3, you can use gc_collect_cycles function to force garbage collector to run it's cycles.Source code viewer
Programming Language: PHP
It is useful to use functions. After the function ends, the data will be considered as excess.Source code viewer
gc_collect_cycles();Programming Language: PHP
Php's variables are global. So they will be available after the loop. If you want to clear the memory then you can use unset or just put into another function then the variables will be cleared. Memory and performance go hand in hand, so it is useful to implement caching in your PHP application. You should not run same processes multiple times if possible. Same applies to sql queries.Source code viewer
function foo() {}Programming Language: PHP
Force clear memory
When you are running out of memory in a single loop then you might need to force clear memory immediately. Then unset is not your way to go. You need to set your variable to NULL, that way memory will be instantly freed.Source code viewer
// Load a huge xml to memory. foreach ($response->xpath('//item') as $key => &$item) { // ... // Clear item and other variables from memory after each loop, or you will run out of it really fast. $item = NULL; }Programming Language: PHP