This recursive function uses over 1.4 MB of RAM, and it’s not freed. All it returns is a single int. How can I free up much more memory?
function bottomUpTree($item, $depth)
{
if ($depth)
{
--$depth;
$newItem = $item << 1;
return array(
bottomUpTree($newItem - 1, $depth),
bottomUpTree($newItem, $depth),
$item
);
}
unset($depth);
unset($newItem);
return array(NULL, NULL, $item);
}
bottomUpTree(0, 7);
Recursive functions will always suck up memory. Each call will use up a bit more until you reach the bottom and start returning. This is unavoidable. Doing
unset()on the function’s parameters won’t help you… they’ve already taken up space on the call stack and can’t be removed until the function returns.One option would be to switch over to an iterative function, but that’s harder to do with a tree-structure.
But most of all, what does this function actually accomplish? You’re returning arrays, but not assigning them anywhere in the calling level, so you’re creating a ton of arrays only to throw them away again immediately.