PHP Memory Allocation and Deallocation

久未见 提交于 2021-02-04 08:17:25

问题


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.

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.

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.

Thank you.

ps. using php 5.4 on linux

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);
}

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);
}

Output:

NULL refcount(2)

NULL refcount(1)

回答1:


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.



来源:https://stackoverflow.com/questions/17816767/php-memory-allocation-and-deallocation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!