PHP reference counting reclaims most values; cyclic references can require the cycle collector.
What It Does and When to Use It
A cyclic pair survives reference counting until cycle collection. 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. gc_collect_cycles() does not guarantee return of all allocated memory to the OS.
Example 1: Basic Operation
A cyclic pair survives reference counting until cycle collection.
<?php
gc_enable();
$a=new stdClass(); $b=new stdClass(); $a->peer=$b; $b->peer=$a;
unset($a,$b); echo gc_collect_cycles(), ' cycles collected';
Example 2: Behavior and Validation
Inspect GC activity rather than assuming every object needs a GC pass.
<?php
$status=gc_status();
foreach (['runs','collected','threshold'] as $key) echo $key, ': ', $status[$key]??'n/a', PHP_EOL;
Practical Example: Application Use
Distinguish cycle collection from releasing allocator memory caches.
<?php
echo 'Before: ',memory_get_usage(true),PHP_EOL;
gc_collect_cycles(); gc_mem_caches();
echo 'After: ',memory_get_usage(true),PHP_EOL;
Important Behavior and Edge Cases
The second example highlights: Inspect GC activity rather than assuming every object needs a GC pass. The practical example adds: Distinguish cycle collection from releasing allocator memory caches.
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 | gc_collect_cycles() does not guarantee return of all allocated memory to the OS. |
Key Takeaways
- PHP reference counting reclaims most values; cyclic references can require the cycle collector.
- Distinguish cycle collection from releasing allocator memory caches.
- Measure the representative workload before changing memory_limit or forcing garbage collection.