PHP: Memory leak in recursive function

2019-09-15 09:47发布

问题:

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.