in reply to Recursion
Some problems are best suited for recursion - like traversing a file system. You don't know how many levels you will descend, so leave that up to recursion.
The same problem can be solved with a while loop, but only if you implement your own stack.
Keep in mind that the faster solution (in general - always exceptions) will be a loop, and for that matter, if you can find a formula to replace the loop, then you will really increase the speed.
Example, summing a list of consecutive numbers, starting with 1:
Both are trivial for this example - and execute in about the same time:my @numbs = qw(1 2 3 4 5 6 7 8 9 10); # loop style sub loop { my $numbs = shift; my $sum; map { $sum += $_; } @{$numbs}; return $sum; } # recursive style - warning: destroys array sub recurse { my ($numbs, $sum) = @_; if (scalar @{$numbs}) { $sum += pop @{$numbs}; &recurse($numbs, $sum); } else { return $sum; } }
But, a relatively famous person by the name of Gauss will tell you that this problem can be solved in one fell swoop with:Benchmark: timing 100000 iterations of Loop, Recursive... Loop: 1 wallclock secs ( 0.70 usr + 0.00 sys = 0.70 CPU) Recursive: 1 wallclock secs ( 0.68 usr + 0.00 sys = 0.68 CPU)
Benchmark: timing 100000 iterations of Guass... Guass: 1 wallclock secs ( 0.49 usr + 0.00 sys = 0.49 CPU)
Thanks to myocom and FouRPlaY for help on the Gauss formula.
|
---|
Replies are listed 'Best First'. | |
---|---|
(tye)Re: Recursion
by tye (Sage) on Nov 15, 2000 at 00:57 UTC | |
RE: Re: Recursion
by FouRPlaY (Monk) on Nov 15, 2000 at 01:11 UTC | |
by tedv (Pilgrim) on Nov 15, 2000 at 21:42 UTC | |
by husker (Chaplain) on Nov 15, 2000 at 22:20 UTC |