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.
In reply to (jeffa) Re: Recursion
by jeffa
in thread Recursion
by lolindrath
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |