On xDebug they limit how many times a function can be nested, are there any disadvantages of nesting functions for so many times?
-
2Doesn't it say it right there? To prevent infinite recursion? And if you're nesting those functions manually, and you need to nest more than 100 times, then you're doing it wrong.Christian– Christian01/14/2013 17:59:24Commented Jan 14, 2013 at 17:59
1 Answer 1
Yes.
Each time you call a function from within another function, you add one level to the stack.
The past function calls have not yet returned, so the memory they claimed for local variables cannot be deallocated; it remains resident until the whole stack is unwound.
Imagine you were to throw an exception from inside a function 1,000 calls deep. In order to generate a stack trace, it would have to walk upward through 1,000 function calls, putting them all into the exception object.
There's nothing you can do with recursion that deep which you couldn't do instead with a well-written loop, and the loop would be both more memory-efficient (as it doesn't have to have the stack frame overhead for each function invocation) and time-efficient (as it doesn't have the overhead of actually performing the function calls you removed).
It is exceedingly unlikely that a program which reaches a recursion level of 1,000 is behaving as intended. More likely, it's stuck in infinite recursion and will eventually exhaust all the system's RAM. Better to kill it earlier.