PHP 8.2: New memory_reset_peak_usage function

Version8.2
TypeNew Feature

PHP 8.2 adds a new function named memory_reset_peak_usage that resets the peak memory usage returned by the memory_get_peak_usage function. This can be helpful in applications that invokes or iterates an action multiple times, and needs to record the peak memory usage of each invocation. Without the ability to reset the memory usage with the new memory_reset_peak_usage function, the memory_get_peak_usage returns the absolute peak memory usage throughout the entire run.

memory_reset_peak_usage function synopsis

/**
 * Resets the peak PHP memory usage
 */
function memory_reset_peak_usage(): void {
}

Usage Examples

$string = str_repeat('a', 1024 * 1024 * 4);
memory_get_peak_usage(); // 4590752

unset($string);

$string = str_repeat('a', 1024 * 1024 * 3);
memory_get_peak_usage(); // 4590752

The snippet above creates a variable $string containing the character a repeated 4194304 times. PHP reports the peak memory usage as 4590752 bytes. Even if the $string variable is destroyed, and written with a string that is smaller than the previous size, the peak memory usage continues to be the same at 4590752 bytes.

With the new memory_reset_peak_usage() function, it is now possible to reset the peak memory usage at any point throughout the lifetime of the request:

  $string = str_repeat('a', 1024 * 1024 * 4);
  memory_get_peak_usage(); // 4590752

  unset($string);
+ memory_reset_peak_usage();

  $string = str_repeat('a', 1024 * 1024 * 3);
  memory_get_peak_usage(); // 3542648

The memory_reset_peak_usage function call right after destruction of the $string variable resets the peak memory PHP engine has recorded, and the subsequent memory_get_peak_usage function call returns the new peak memory usage value.

Backwards Compatibility Impact

memory_reset_peak_usage is a new function added in PHP 8.2, and it is not possible to backport this function to older PHP functions using user-land PHP functions because memory_reset_peak_usage interacts with internally stored values of the PHP engine.

For more finer control and inspection of PHP memory usage that works across multiple PHP versions, consider using dedicated profiler. Some of the free and open-source profilers include XDebug Profiler, XHProf, PHP Memory Profiler. Alternately, commercial PHP profilers such as Tideways and Blackfire also offer finer memory profiling.


Implementation