In a PHP program, I sequentially read a bunch of files (with file_get_contents
), gzdecode
them, json_decode
the result, analyze the contents, throw most of it away, and store about 1% in an array.
Unfortunately, with each iteration (I traverse over an array containing the filenames), there seems to be some memory lost (according to memory_get_peak_usage
, about 2-10 MB each time). I have double- and triple-checked my code; I am not storing unneeded data in the loop (and the needed data hardly exceeds about 10MB overall), but I am frequently rewriting (actually, strings in an array). Apparently, PHP does not free the memory correctly, thus using more and more RAM until it hits the limit.
Is there any way to do a forced garbage collection? Or, at least, to find out where the memory is used?
Call
memory_get_peak_usage()
after each statement, and ensure youunset()
everything you can. If you are iterating withforeach()
, use a referenced variable to avoid making a copy of the original (foreach()).If PHP is actually leaking memory a forced garbage collection won't make any difference.
There's a good article on PHP memory leaks and their detection at IBM
In PHP >= 5.3.0, you can call
gc_collect_cycles()
to force a GC pass.Note: You need to have
zend.enable_gc
enabled in yourphp.ini
enabled, or callgc_enable()
to activate the circular reference collector.