in reply to Re: Is it possible to create a sub exclusive to a sub?
in thread Is it possible to create a sub exclusive to a sub?
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Is it possible to create a sub exclusive to a sub? (nasty memory leak)
by TedPride (Priest) on Sep 19, 2004 at 03:49 UTC | |
|
Re^3: Is it possible to create a sub exclusive to a sub? (nasty memory leak)
by dragonchild (Archbishop) on Sep 19, 2004 at 04:34 UTC | |
by ihb (Deacon) on Sep 19, 2004 at 10:46 UTC | |
by dragonchild (Archbishop) on Sep 19, 2004 at 13:56 UTC | |
by ihb (Deacon) on Sep 19, 2004 at 14:30 UTC | |
by dragonchild (Archbishop) on Sep 19, 2004 at 18:30 UTC | |
|