PHP: Memory leak in recursive function

a 夏天 提交于 2019-12-25 01:31:20

问题


I have a recursive function which, given an id, builds up a directory path. The thing is, it doesn't free up the space, so starting with a memory consumption of 15MB after 1761 folders, the memory consumption is at about 150MB which is not healthy.

this is the function:

private function buildDirectoryPath($iId, $sDir = "") 
{    
    $oFolder = Folders::getFolder($iId);

    if (!empty($sDir)) $sDir = $oFolder->getName() . "/" . $sDir;
        else $sDir = $oFolder->getName(). $sDir;

    if ($oFolder->getParentId() > 0)
        $sDir = $this->buildDirectoryPath($oFolder->getParentId(), $sDir);

    return $sDir;
}

and this is how i call it (inside the loop of the folders):

foreach ($aFolders as $aFolder) {           
    $sFolderPath = $this->buildDirectoryPath($aFolder["fol_id"]);
}

so to be honest, i haven't written many recursive functions yet, so i am open to any adjustments

edit, adding the Folders::getFolder static method:

static public function getFolders($sAppCode,
                                      $iParentId = 0)
    {

        $oDb = Zend_Registry::get('db');
        $oSelect = $oDb
            ->select()
            ->from('folders')
            ->where('folders.fol_deleted_user_id = 0')
            ->order('folders.fol_name ASC');


        if ($iParentId >= 0) {
            $oSelect->where('folders.fol_parent_id = ' . (int)$iParentId);
        }

        $aFolders = $oDb->fetchAll($oSelect);

//added the $object = null later

        $oDb = null;
        $oSelect = null;
        $oAppSelector = null;
        return $aFolders;
    }

edit2: if i won't find an easy solution, my plan b would be to put cache the paths, so i don't need to build them everything. its just that i have to alter a lot of code inside the app


回答1:


Why not use RecursiveDirectoryIterator or DirectoryIterator for folder parsing?

Your code is very incomplete. We need to see what happens outside this. Where you store data in an array or what you do that can take up memory. If you build a tree of the files in 2000 folders, 150MB is very plausible.



来源:https://stackoverflow.com/questions/17188469/php-memory-leak-in-recursive-function

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