Reference counts normally free values promptly, while cycle detection handles unreachable circular references.
What It Does and When to Use It
Demonstrate a self-referential object requiring the cycle collector. Current allocations answer how much PHP holds now; peak allocations expose workload spikes that can exceed the process limit.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. Do not disable garbage collection globally as a first response to memory problems.
Example 1: Basic Operation
Demonstrate a self-referential object requiring the cycle collector.
<?php
$node=new stdClass(); $node->self=$node;
unset($node); echo 'Cycles: ',gc_collect_cycles();
Example 2: Behavior and Validation
Show reference-counted values can be freed without cyclic GC.
<?php
$items=array_fill(0,1000,42); unset($items);
echo 'Usage: ',memory_get_usage(false);
Practical Example: Application Use
Always restore GC state after a controlled experiment.
<?php
gc_disable();
try { echo gc_enabled() ? 'enabled' : 'disabled'; }
finally { gc_enable(); }
Important Behavior and Edge Cases
The second example highlights: Show reference-counted values can be freed without cyclic GC. The practical example adds: Always restore GC state after a controlled experiment.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| memory_get_usage versus memory_get_peak_usage | Current allocations answer how much PHP holds now; peak allocations expose workload spikes that can exceed the process limit. |
| Choosing safely | Measure the representative workload before changing memory_limit or forcing garbage collection. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming successful execution proves the result is usable | Check the return value, required extension, and observable output of the specific operation. |
| Ignoring runtime and environment differences | Verify PHP version, SAPI, operating system, service access, and permissions before deployment. |
| Skipping operational constraints | Do not disable garbage collection globally as a first response to memory problems. |
Key Takeaways
- Reference counts normally free values promptly, while cycle detection handles unreachable circular references.
- Always restore GC state after a controlled experiment.
- Measure the representative workload before changing memory_limit or forcing garbage collection.