PHP 内存分配和释放 [英] PHP Memory Allocation and Deallocation

查看:61
本文介绍了PHP 内存分配和释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在运行一个长时间运行的脚本来处理内存敏感数据(大量).我(认为)我在整个长时间运行的过程中正确销毁大型对象方面做得很好,以节省内存.

So, I am running a long-running script that is dealing with memory sensitive data (large amounts of it). I (think) I am doing a good job of properly destroying large objects throughout the long running process, to save memory.

我有一个连续输出当前内存使用情况的日志(使用 memory_get_usage()),我没有注意到内存使用量的上升和下降(重要的).这告诉我我可能在内存管理方面做了正确的事情.

I have a log that continuously outputs current memory usage (using memory_get_usage()), and I do not notice rises and drops (significant ones) in memory usage. Which tells me I am probably doing the right thing with memory management.

但是,如果我登录到服务器并运行 top 命令,我会注意到处理此脚本的 apache 进程永远不会释放内存(至少通过 top 命令可见).它只是保持在最高的内存使用量,即使 php 报告的当前内存使用量要低得多.

However, if I log on to the server and run a top command, I notice that the apache process that is dealing with this script never deallocates memory (at least visibly though the top command). It simply remains at the highest memory usage, even if the current memory usage reported by php is much, much lower.

所以,我的问题是:如果内存没有真正释放回服务器,我尝试保存内存是否会徒劳?或者我在这里遗漏了什么.

So, my question is: are my attempts to save memory futile if the memory isnt really being freed back to the server? Or am I missing something here.

谢谢.

ps.在 linux 上使用 php 5.4

ps. using php 5.4 on linux

pps.对于那些想要代码的人,这是一个基本的表示:

pps. For those who want code, this is a basic representation:

function bigData()
{
    $obj = new BigDataObj();
    $obj->loadALotOfData();

    $varA = $obj->getALotOfData();

    //all done
    $obj = NULL;
    $varA = NULL;
    unset($obj,$varA);
}

更新:按照 hek2mgl 的建议,我运行了 debug_zval_dump(),输出对我来说似乎是正确的.

update: as hek2mgl recommended, I ran debug_zval_dump(), and the output, to me, seems correct.

function bigData()
{
    $obj = new BigDataObj();
    $obj->loadALotOfData();

    //all done
    $obj = NULL;

    debug_zval_dump($obj);

    unset($obj);

    debug_zval_dump($obj);
}

输出:

NULL refcount(2)

NULL refcount(1)

推荐答案

PHP 有一个垃圾收集器.它将为引用计数设置为 0 的变量容器释放内存,这意味着不再存在用户空间引用.

PHP has a garbage collector. It will free memory for variable containers which reference count is set to 0, meaning that no userland reference exists anymore.

我想仍然存在对您可能认为已清除的变量的引用.需要查看您的代码以向您展示问题所在.

I guess there are still references to variables which you might think to have cleaned. Need to see your code to show you what is the problem.

这篇关于PHP 内存分配和释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆