Reset Peak Memory Usage using memory_reset_peak_usage in PHP 8.2

Reset Peak Memory Usage using memory_reset_peak_usage in PHP 8.2

PHP provides the memory_get_peak_usage function that allows to get the absolute peak memory usage, in bytes, allocated by PHP script. However, without reset the memory usage, it is hard to determine how much memory takes some of the code parts. Since PHP 8.2, we can the use memory_reset_peak_usage function that allows to reset the peak memory usage returned by the memory_get_peak_usage function.

The following example shows that the peak memory usage continues to be the similar, even if the str variable is destroyed:

<?php

echo memory_get_peak_usage().PHP_EOL; // 427952

$str = str_repeat('0', 10000000);;
echo memory_get_peak_usage().PHP_EOL; // 10878320

unset($str);
echo memory_get_peak_usage().PHP_EOL; // 10878400

Using the memory_reset_peak_usage function, it is possible to reset the peak memory usage. The following example shows that the peak memory usage is greatly decreased after destructing str variable:

<?php

echo memory_get_peak_usage().PHP_EOL; // 427952

$str = str_repeat('0', 10000000);;
echo memory_get_peak_usage().PHP_EOL; // 10878320

unset($str);
memory_reset_peak_usage();
echo memory_get_peak_usage().PHP_EOL; // 392736

Leave a Comment

Cancel reply

Your email address will not be published.