没有不值得去解决的问题,也没有不值得去学习的技术!

Analyze PHP Memory Allocation and How unset() Reduces Actual Script Memory Usage

Based on a memory_get_usage() example, after adjustments

1. Reference URL: https://www.php.net/manual/zh/function.memory-get-usage.php

2. Based on a memory_get_usage() example, after adjustments, as shown in Figure 1, the code is as follows:

Based on a memory_get_usage() example, after adjustments
Figure 1
PHP

//这只是个例子,下面的数字取决于你的系统

echo memory_get_usage()/1024/1024 . " MB\n"; // 0.37361145019531 MB

$a = str_repeat("Hello", 424200);

echo memory_get_usage()/1024/1024 . " MB\n"; // 4.3736343383789 MB

unset($a);

echo memory_get_usage()/1024/1024 . " MB\n"; // 0.37361145019531 MB

echo memory_get_peak_usage()/1024/1024 . " MB\n"; // 4.3739242553711 MB

3. The execution result shows that unset() is effective in reducing the actual amount of memory used by the PHP script.

Plaintext

0.37361145019531 MB 4.3736343383789 MB 0.37361145019531 MB 4.3739242553711 MB

4. In Yii 2.0, running the same code and checking the memory usage in the debug data shows a value of Memory 11.356 MB, which is consistent with memory_get_peak_usage() – returns the peak of memory allocated to PHP. As shown in Figure 2

In Yii 2.0, running the same code and checking the memory usage in the debug data shows a value of Memory 11.356 MB, which is consistent with memory_get_peak_usage() - returns the peak of memory allocated to PHP.
Figure 2
Plaintext

7.3560180664062 MB 11.35604095459 MB 7.3560180664062 MB 11.356330871582 MB

5. Repeat step 2, setting real_usage to TRUE to get the total size of memory allocated by the system, including unused pages. If not set or set to FALSE, only the actual used memory amount is reported. The execution result shows that unset() is still effective in reducing the total size of memory allocated by the system for the PHP script.

PHP

// 这只是个例子,下面的数字取决于你的系统

echo memory_get_usage(true)/1024/1024 . " MB\n"; // 0.37361145019531 MB

$a = str_repeat("Hello", 424200);

echo memory_get_usage(true)/1024/1024 . " MB\n"; // 4.3736343383789 MB

unset($a);

echo memory_get_usage(true)/1024/1024 . " MB\n"; // 0.37361145019531 MB

echo memory_get_peak_usage(true)/1024/1024 . " MB\n"; // 4.3739242553711 MB

Plaintext

2 MB 6 MB 2 MB 6 MB

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系