编程

PHP 8.2 新特性 —— 新增 memory_reset_peak_usage 函数

693 2022-12-01 18:39:15

PHP 8.2 新增了一个名为  memory_reset_peak_usage 函数,用以重置 memeory_get_peak_usage 返回的内存使用峰值。这对于调用或迭代一个动作多次的应用是有用的,需要记录每次调用的内存峰值。没有新增的 memory_reset_peak_usage 函数重置内存使用率的能力,memory_get_peak_usage 返回整个运行期间内存使用高峰的绝对值。

memory_reset_peak_usage 函数概要

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

用例

$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

上面的代码创建了一个 $string 变量,包含字符 a 重复 4194304 次,PHP 报告了内存使用的峰值是 4590752 bytes。即使 $string 变量销毁了,并用比之前小的字符重写,内存使用峰值依然是  4590752 bytes。

有了新增的 memory_reset_peak_usage() 函数,现在可以在请求生命周期内的任何一个点重置内存使用峰值了:

  $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

memory_reset_peak_usage 在 $string 变量销毁后马上调用,重置已记录的 PHP 引擎峰值,随后着 memory_get_peak_usage 函数调用返回新的内存使用峰值。

向下兼容性影响

memory_reset_peak_usage 是 PHP 8.2 中的新函数,不可能在旧版的 PHP 中使用用户空间的 PHP 函数 backport 该函数,因为 memory_reset_peak_usage 与 PHP 引擎内部存储的值有交互。

为了在跨多个PHP 版本中更好的控制及检测 PHP 内存使用,可以考虑使用专用的分析器。有一些开源免费的分析器 如 XDebug、XHProf、PHP Memory Profiler。另外,商用的 PHP 分析器比如 Tideways 和 Blackfire 也提供了高质量的内存分析。