Memory and garbage collection
suggest changeIn standard PHP web environments (such as PHP-FPM), the PHP interpreter uses a request-based lifecycle: all memory allocated during an HTTP request is automatically wiped when the request terminates. However, in modern PHP—where long-running processes, CLI workers (Laravel Horizon, Symfony Messenger), and application servers (RoadRunner, Swoole) run continuously—understanding reference counting, cyclic garbage collection, and memory limits is crucial to avoid memory leaks.
1. Monitoring Memory Usage
PHP provides built-in functions to inspect real-time memory consumption:
<?php
// Formatted memory helper
function formatBytes(int $bytes): string {
$units = ['B', 'KB', 'MB', 'GB'];
$power = $bytes > 0 ? floor(log($bytes, 1024)) : 0;
return sprintf("%.2f %s", $bytes / pow(1024, $power), $units[$power]);
}
// Current memory allocated to PHP scripts
echo "Current usage: " . formatBytes(memory_get_usage()) . "\n";
// Real memory allocated by the operating system (system heap)
echo "Real OS allocation: " . formatBytes(memory_get_usage(true)) . "\n";
// Peak memory reached during script execution
echo "Peak usage: " . formatBytes(memory_get_peak_usage(true)) . "\n";
Configuring the Memory Limit
The memory_limit directive sets the maximum memory a script may allocate before throwing a fatal Allowed memory size exhausted error:
<?php
// Inspect current limit
echo ini_get('memory_limit'); // e.g. "128M"
// Dynamically raise limit for heavy batch processing
ini_set('memory_limit', '512M');
// Set unlimited memory (use with extreme caution in CLI scripts)
ini_set('memory_limit', '-1');
2. Reference Counting and Copy-on-Write (COW)
Every PHP variable is represented internally in the Zend Engine by a container called a zval. For reference-counted types (strings, arrays, objects, resources), the zval maintains a refcount counter tracking how many symbols point to that value.
Copy-on-Write (COW)
Assigning an array to another variable does not duplicate the memory immediately:
<?php
$a = range(1, 100_000); // Allocates memory for array
echo formatBytes(memory_get_usage()) . "\n"; // e.g. ~4.0 MB
$b = $a; // COW: $b points to the exact same zval (refcount = 2); 0 additional bytes
echo formatBytes(memory_get_usage()) . "\n"; // Still ~4.0 MB
$b[] = 100_001; // Mutation triggers duplication: a new copy is now allocated
echo formatBytes(memory_get_usage()) . "\n"; // Jumps to ~8.0 MB
When a variable leaves scope or is passed to unset(), its refcount decrements. When refcount reaches 0, the Zend Engine immediately frees the memory back to the allocator.
3. Circular References and Cyclic Garbage Collection
Simple reference counting fails when objects reference each other cyclically:
<?php
class Node {
public ?Node $neighbor = null;
public string $payload;
public function __construct(string $payload) {
$this->payload = $payload;
}
}
function createCycle(): void {
$a = new Node("A");
$b = new Node("B");
// Circular reference
$a->neighbor = $b;
$b->neighbor = $a;
// When the function exits, $a and $b go out of scope.
// However, because $a->neighbor references $b and $b->neighbor references $a,
// their refcounts drop to 1, NOT 0!
// Plain reference counting cannot free them.
}
createCycle();
The Cycle Collector
To reclaim circular references, PHP incorporates a Cyclic Garbage Collector (based on the Bacon & Rajan algorithm). Whenever an object's refcount decreases without hitting zero, PHP suspects a possible garbage cycle and places the zval into a circular buffer (defaulting to 10,000 roots).
When the buffer fills, the garbage collector runs:
- It simulates decrementing refcounts across internal references.
- Any nodes whose effective refcount reaches zero are confirmed as isolated cycles (garbage).
- The collector sweeps and frees the dead memory.
Controlling the Garbage Collector
<?php
// Check if GC is currently active
echo "GC Enabled: " . (gc_enabled() ? "Yes" : "No") . "\n";
// Manually trigger garbage collection run
$collectedCycles = gc_collect_cycles();
echo "Reclaimed cycles: $collectedCycles\n";
// Inspect detailed GC statistics (PHP 7.3+; more fields since PHP 8.3)
$stats = gc_status();
print_r($stats);
/*
Array
(
[running] =>
[protected] =>
[full] =>
[runs] => 1
[collected] => 420
[threshold] => 10001
[buffer_size] => 16384
[roots] => 0
[application_time] => 0.0004694
[collector_time] => 1.9E-6
[destructor_time] => 0
[free_time] => 0
)
*/
// Disable/enable GC (useful for CPU-critical loops where allocations are strictly linear)
gc_disable();
// ... CPU-intensive tasks ...
gc_enable();
4. Preventing Leaks with WeakReference and WeakMap
PHP 7.4 introduced WeakReference, and PHP 8.0 introduced WeakMap. A weak reference allows you to hold a pointer to an object without incrementing its refcount. When all strong references are removed, the object is destroyed immediately:
<?php
class CacheItem {
public string $data;
public function __construct(string $data) {
$this->data = $data;
}
}
$item = new CacheItem("Sensitive user profile");
$weakRef = WeakReference::create($item);
// Retrieve the object if it still exists
var_dump($weakRef->get()); // object(CacheItem)
// Remove the only strong reference
unset($item);
// The weak reference automatically evaluates to null
var_dump($weakRef->get()); // NULL (Memory was immediately freed!)
Using WeakMap for Object Metadata
A WeakMap uses objects as keys without preventing those objects from being garbage-collected:
<?php
$cache = new WeakMap();
$user = new stdClass();
$cache[$user] = ["role" => "admin", "last_login" => time()];
echo count($cache); // 1
unset($user); // When $user is destroyed, its entry in WeakMap is automatically removed!
echo count($cache); // 0
Best Practices for Long-Running Workers
- Explicitly Free Large Payloads in Daemon Loops: Call
unset($largeDataPayload)at the end of each worker iteration. - Use Generators (
yield) for Streaming: When reading thousands of database rows or gigabytes of log files, stream data using PHP generators instead of loading whole collections into an in-memory array. - Periodically Run
gc_collect_cycles(): In background consumers (RabbitMQ, SQS, Redis workers), invokegc_collect_cycles()every N jobs to purge any circular references before memory climbs.