Memory management
Learn to manage memory with memory_get_usage() and breaking reference cycles.
memory_get_usage and peak
PHP allocates memory on every request and the garbage collector reclaims objects that are no longer reachable. memory_get_usage gives the current consumption in bytes; memory_get_peak_usage returns the highest point reached since the start of the request.
With true both report the total allocated, with false only the used portion. Watching the peak is usually enough to spot a memory leak; calling memory_get_usage at every step adds overhead.
Circular references and Spl data structures
When an object holds a reference back to itself (a circular reference) the garbage collector cannot reclaim it automatically, and memory leaks. PHP's GC scans for cycles periodically but slowly; you can trigger it manually with gc_collect_cycles.
SplFixedArray is a fixed-size array that uses less memory; SplStack and SplQueue provide LIFO/FIFO access with built-in methods. For stack work SplStack uses less memory than a plain array with array_push and array_pop.
Exercise Work with SplStack and SplQueue
Create an SplStack and add 'apple', 'pear', 'cherry' with push. Create an SplQueue and add 'apple', 'pear' with enqueue. Print echo $stack->count() . "\n" and echo $queue->count() . "\n". Then pop and dequeue one item each with echo $stack->pop() . "\n" and echo $queue->dequeue() . "\n".
Show example solution
Start with $stack = new SplStack();. push('apple'), push('pear'), push('cherry'). $queue = new SplQueue(); enqueue('apple'), enqueue('pear'). echo $stack->count() . "\n"; echo $queue->count() . "\n"; echo $stack->pop() . "\n"; echo $queue->dequeue() . "\n";.
Example solution:
<?php
$stack = new SplStack();
$stack->push('apple');
$stack->push('pear');
$stack->push('cherry');
$queue = new SplQueue();
$queue->enqueue('apple');
$queue->enqueue('pear');
echo $stack->count() . "\n";
echo $queue->count() . "\n";
echo $stack->pop() . "\n";
echo $queue->dequeue() . "\n";
Test yourself
-
Match the Spl data structures
- SplStack
- LIFO stack
- SplQueue
- FIFO queue
- SplFixedArray
- Fixed-size array
- memory_get_peak_usage
- Peak memory
-
Complete the SplStack push call
$stack = new SplStack(); $stack->____('apple'); $stack->push('pear'); echo $stack->count() . "\n";Show answer
$stack = new SplStack(); $stack->push('apple'); $stack->push('pear'); echo $stack->count() . "\n"; -
Why is a circular reference a problem?
- It gives faster access
- It clashes with SplStack
- The garbage collector cannot reclaim the object automatically
- It returns memory automatically
Show answer
The garbage collector cannot reclaim the object automatically — Correct. With a circular reference the GC cannot reclaim the object, so memory leaks.