PHP Memory Usage Information

The less you strain your system, the better performance you get. Managing memory effectively plays a critical role in enhancing application performance. In PHP 5 and above, there are two essential functions to analyze memory usage: memory_get_usage() and memory_get_peak_usage().
1. memory_get_usage()
This function returns the current amount of RAM utilized by the code in bytes.
2. memory_get_peak_usage()
This function returns the peak amount of RAM allocated for the code in bytes.
Let’s examine these with a simple example:
$initialMemory = memory_get_usage();
// Use some memory
for ($i = 0; $i < 100000; $i++) {
$array[] = base64_encode(sha1(md5($i)));
// Encode the value of $i into md5, then sha1, and finally base64 before storing it in the array
}
foreach ($array as $value) {
base64_decode($value);
// Decode the base64 values in the array
}
for ($i = 0; $i < 50000; $i++) {
unset($array[$i]);
// Remove half of the values from the array
}
$finalMemory = memory_get_usage();
$peakMemory = memory_get_peak_usage();
// Display memory usage in bytes, KB, and MB
echo "Initial Memory = {$initialMemory} bytes
";
echo "Initial Memory = " . round($initialMemory / 1024, 2) . " KB
";
echo "Initial Memory = " . round($initialMemory / 1024 / 1024, 2) . " MB
";
echo "Final Memory = {$finalMemory} bytes
";
echo "Final Memory = " . round($finalMemory / 1024, 2) . " KB
";
echo "Final Memory = " . round($finalMemory / 1024 / 1024, 2) . " MB
";
echo "Peak Memory = {$peakMemory} bytes
";
echo "Peak Memory = " . round($peakMemory / 1024, 2) . " KB
";
echo "Peak Memory = " . round($peakMemory / 1024 / 1024, 2) . " MB
";
Output:
Initial Memory = 127832 bytes
Initial Memory = 124.84 KB
Initial Memory = 0.12 MB
Final Memory = 8252608 bytes
Final Memory = 8059.19 KB
Final Memory = 7.87 MB
Peak Memory = 15853936 bytes
Peak Memory = 15482.36 KB
Peak Memory = 15.12 MB
As shown above, the Initial Memory indicates the memory usage at the start of the script. The Final Memory shows the usage after performing operations, dropping from 15.12 MB to 7.87 MB. Finally, the Peak Memory represents the highest memory usage recorded during execution, which in this case is 15.12 MB.
Using these functions while writing your code is recommended to ensure better performance.
Stay Curious, Stay Knowledgeable...
PHP,Version,Sürüm,Hash Şifreleme,MD5,SHA1,Nasıl Yapılır,Kontrol,Fonksiyon,Performans