Asks PHP's allocator to release eligible free memory pages back to the system.
What It Does and When to Use It
Read the number of bytes returned to the allocator or OS. APCu stores local application data, Redis is external and can be shared among hosts, and OPcache stores compiled code.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. It returns the number of bytes freed from the allocator, not live object memory.
Example 1: Basic Operation
Read the number of bytes returned to the allocator or OS.
<?php
$freed = gc_mem_caches();
echo "Allocator memory released: {$freed} bytes";
Example 2: Behavior and Validation
Release references before requesting allocator cache cleanup.
<?php
$values = array_fill(0, 10_000, str_repeat('a', 40));
unset($values);
gc_collect_cycles();
echo gc_mem_caches();
Practical Example: Application Use
Compare allocated memory before and after; the values are not a guaranteed reduction.
<?php
$current = memory_get_usage(true);
$freed = gc_mem_caches();
echo 'Before: ', $current, '; freed: ', $freed,
'; after: ', memory_get_usage(true);
Important Behavior and Edge Cases
The second example highlights: Release references before requesting allocator cache cleanup. The practical example adds: Compare allocated memory before and after; the values are not a guaranteed reduction.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| APCu versus Redis and OPcache | APCu stores local application data, Redis is external and can be shared among hosts, and OPcache stores compiled code. |
| Choosing safely | Define TTL, invalidation, and concurrency behavior separately from the cache storage API. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming a cache is shared across multiple servers | Confirm process- and host-level cache scope; use a distributed store when needed. |
| Never invalidating cached data | Set a TTL or versioned cache key and test release-time invalidation. |
| Skipping operational constraints | It returns the number of bytes freed from the allocator, not live object memory. |
Key Takeaways
- Asks PHP's allocator to release eligible free memory pages back to the system.
- Compare allocated memory before and after; the values are not a guaranteed reduction.
- Define TTL, invalidation, and concurrency behavior separately from the cache storage API.