PHP & Zend Engine (50 Qs)•Part 2: Zend Engine Internals, OPcache & Memory Architecture (11 - 24)
How does Reference Counting and the Circular Reference Garbage Collector work in PHP?
senior LevelMost AskedMemory ManagementSystem Design
In Simple Words:
Complex values (strings, arrays, objects) maintain a refcount field. When variable assignments point to an object, refcount increments; when variables go out of scope, it decrements. When refcount hits 0, memory is freed immediately.
Circular References:
If object A references B and B references A, their refcounts never reach 0. PHP uses a Root Buffer Cycle Collector (runs every 10,000 suspect objects) that runs a trial deletion to detect and free circular memory islands.