15
207 天前
php 碰到内存“泄露”问题,有几个方面
1. “全局变量” 或者 “常驻依赖注入容器对象” 的膨胀导致内存不够,比如 orm 中 EntityManager 没有及时 clear 追踪的不再被使用的数据库实体对象。
2. 代码逻辑“死循环” 导致内存不够。
3. 使用了存在内存泄露 bug 的 c/c++拓展。
当接楼上我的回答,当 php 内存达到设置值时,比如 32M 时会自动触发垃圾回收,所以没有必要手动 gc_collect_cycles();
php 7.3 之后有个 gc_status();可以看 gc 状态
```
[email protected]:~$ cat 2.php
function fun1()
{
$a = ['hello'];
$a[] = &$a;
}
while(true) {
var_dump(gc_status());
fun1();
var_dump(gc_status());
gc_collect_cycles();
echo memory_get_usage() . "\n";
sleep(1);
}
[email protected]:~$ '/home/zjsxwc/php74/bin/php' 2.php
array(4) {
["runs"]=>
int(0)
["collected"]=>
int(0)
["threshold"]=>
int(10001)
["roots"]=>
int(0)
}
array(4) {
["runs"]=>
int(0)
["collected"]=>
int(0)
["threshold"]=>
int(10001)
["roots"]=>
int(1)
}
365496
array(4) {
["runs"]=>
int(1)
["collected"]=>
int(1)
["threshold"]=>
int(10001)
["roots"]=>
int(0)
}
array(4) {
["runs"]=>
int(1)
["collected"]=>
int(1)
["threshold"]=>
int(10001)
["roots"]=>
int(1)
}
365496
```