Syntactic Confectionery Delight | |
PerlMonks |
Re^4: Is it possible to create a sub exclusive to a sub? (nasty memory leak)by ihb (Deacon) |
on Sep 19, 2004 at 10:46 UTC ( [id://392159]=note: print w/replies, xml ) | Need Help?? |
you say the anonymous sub isn't a closure Indeed I did. I expressed myself poorly and I've rephrased my post to hopefully better express what I meant. (But first, to avoid any confusion: a closure is a subroutine, named or anonymous, that binds its lexical context.) A lexical anonymous recursive subroutine is by necessity a closure. What I meant was that the subroutine, if written as a named subroutine, isn't a closure. By making it lexical and anonymous you make it one though, but the only lexical surrounding it is using is its own declaration. The memory leak comes from that inside the subroutine, you use $_fibo. That makes $_fibo reference a subroutine that references $_fibo. Thus, $_fibo is a circular reference and refcount will never drop below two and won't be garbage collected. This below illustrates what I've just said. On my perl, and probably yours too, the following will print the same for each iteration. This is because $foo gets garbage collected and the memory slot may be is currently is reused. (Since this just happens to be the implementation you can't trust it to always perform the same though.) If you change the subroutine to bind $foo you get Here we see that the memory slot isn't being reused. It can also be interesting to look at the output of the &Dump subroutine in the Devel::Peek package. (For extra effect, dump the sub after doing differently many recursive calls.) I hope I managed to express myself better this time. ihb Read argumentation in its context!
In Section
Seekers of Perl Wisdom
|
|