What are the potential implications of a deep call stack in Perl?
- I was told that the following portion of code is deeply recursive. However I don't understand how - can someone explain?
- If so, what are the associated implications?
Note:
Trivial example
check:
# Grab some data held in a file
while ((ReadFile ()) != 0 ) {
if ((checkSomething ()) != 1) {
# value found, check file again
next check;
} else {
blah ($doo, $foo);
}
}
Update:
- Thank you for the correction.
What are the implications of the following,开发者_运维知识库 in terms of memory consumption - this is not recursion as far as I understand and after reviewing other questions:
sub D { .. } sub C { D (); } sub B { C (); } sub A { while (true) { B (); } }
Your second example is also not an example of recursion. That's just an example of what I would informally call "chained subroutine calls" - I don't believe there's a formal term for it. Recursion requires that a subroutine call itself, either directly or through some set of intermediaries.
For example, if subroutine D had a call in it to A, B, or C under certain conditions, that would be recursion.
As for deep call stacks, the answer is it depends on:
- how deep
- how many arguments you're passing in each one
- how much memory your program can allocate
Each time you call a subroutine, it adds a new frame on the call stack. That frame remains until the subroutine completes. The size of this stack frame depends primarily on the length of your arguments list, plus some fixed overhead.
So in this case, you'd have a stack frame with four elements.
If your call chain gets too deep and each entry has a long list of arguments, you'll eventually run out of space for the call stack. This is called a Stack Overflow. :)
As others have said, your code isn't recursive, so don't worry about it. However, it'll be cleaner and easier to read if you eliminate the useless if
branch by making the condition for the else
branch the only one, and drop the icky label:
while ((ReadFile ()) != 0 ) {
if ((checkSomething ()) == 1) {
blah ($doo, $foo);
}
}
There's no recursion in that code.
Your code may have recursion, but it's not shown in the code you offered.
I agree with JS Bangs, but another alternative to the icky label would be to use a continue statement instead of the "next check". JS Bangs is the best for this code, but continue statements have their place.
精彩评论