问题描述
我有一个递归函数,给定一个id,它会建立一个目录路径.事实是,它无法释放空间,因此从1761个文件夹之后的15MB内存消耗开始,内存消耗约为150MB,这是不健康的.
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.
这是函数:
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
编辑,添加Folders :: getFolder静态方法:
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:如果我找不到简单的解决方案,我的计划b将是对路径进行缓存,因此我不需要全部构建它们.只是我必须在应用程序内部更改很多代码
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
推荐答案
为什么不使用 RecursiveDirectoryIterator
或 DirectoryIterator
用于文件夹解析?
Why not use RecursiveDirectoryIterator
or DirectoryIterator
for folder parsing?
您的代码非常不完整.我们需要看看在此之外发生了什么.在数组中存储数据的位置或执行此操作可能会占用内存.如果您在2000个文件夹中构建一棵文件树,那么150MB似乎很合理.
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.
这篇关于PHP:递归函数中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!