Can someone please explain under what circumstances gc_collect_cycles function can be useful? Should it be called before a substantial memory utilization is about to take place?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
PHP has "Garbage Collector" enabled by default. It is used to free memory used by "garbage".
gc_collect_cycles()
forces collection of any existing garbage cycles. It returns number of collected (freed) cycles (objects, variable values ...). Enabled Garbage Collector calls this function internally from time to time to free resources. In most cases PHP script lives very short time. In this case all garbage will be destroyed in the end of work without any garbage collection.Sometimes it's needed to manage GC manually:
gc_disable()
can speed up some long operations, but also results in some memory overheads.gc_collect_cycles()
could be used to specify the right moments of GC.Another one reason to use
gc_collect_cycles()
- debugging. Assume, you want to know what is the memory consumption of some block of code withmemory_get_usage()
. You need to disable GC first, elsewhere you'll get wrong results. After that you want to separate the time consumed by GC and by your application. So callgc_collect_cycles()
and measure timings/memory before and after.Little example:
Will output:
This means that only
$b
was destroyed when it was asked. Other$a1
and$a2
has cyclic references, and it'sname
properties also consume memory. Two objects + two strings = 4 (removed bygc_collect_cycles()
).