What I don't like about having anonymous subroutines that aren't closures inside subroutines is that the anonymous subroutine is created for each invocation of the surrounding subroutine. In your examples that means that each time &fibonacci is executed, a new recursive subroutine is created. Having anonymous recursive subroutines that aren't closures is even worse. Rephrase: Writing recursively defined subroutines that doesn't use the surrounding lexical scope as lexical anonymous recursive subroutines is even worse, since it creates a "circular closure". $_fibo in our example above is a circular reference and a very bad such since you can't break the circle manually. That's a pretty nasty memory leak.
I would prefer to define the recursive subroutine once, rewriting your example to
{ my $_fibo; $_fibo = sub { my $v = shift; $v > 1 ? $_fibo->($v - 1) + $_fibo->($v - 2) : 1; }; sub fibonacci { $_fibo->(@_) } }
ihb
Read argumentation in its context!
In reply to Re^2: Is it possible to create a sub exclusive to a sub? (nasty memory leak)
by ihb
in thread Is it possible to create a sub exclusive to a sub?
by punkish
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |