Measure baseline, peak and retained memory across iterations to diagnose growing allocations.
What It Does and When to Use It
Compare memory allocation before and after a workload. 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. Separate transient peaks from retained references and extension-level native allocations.
Example 1: Basic Operation
Compare memory allocation before and after a workload.
<?php
$before=memory_get_usage(true);
$values=range(1,5000);
echo 'Allocated bytes: ',memory_get_usage(true)-$before; unset($values);
Example 2: Behavior and Validation
Reset the peak counter when measuring a specific PHP 8.2+ operation.
<?php
memory_reset_peak_usage();
$data=array_fill(0,5000,'row');
echo 'Peak bytes: ',memory_get_peak_usage(true);
Practical Example: Application Use
Sample memory across jobs and investigate sustained growth, not isolated spikes.
<?php
$samples=[];
for ($i=0;$i<3;$i++) { $samples[]=['job'=>$i,'mem'=>memory_get_usage(false)]; }
print_r($samples);
Important Behavior and Edge Cases
The second example highlights: Reset the peak counter when measuring a specific PHP 8.2+ operation. The practical example adds: Sample memory across jobs and investigate sustained growth, not isolated spikes.
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 | Separate transient peaks from retained references and extension-level native allocations. |
Key Takeaways
- Measure baseline, peak and retained memory across iterations to diagnose growing allocations.
- Sample memory across jobs and investigate sustained growth, not isolated spikes.
- Measure the representative workload before changing memory_limit or forcing garbage collection.