Depends. Each recursive call to function places another entry on the system stack. So it's possible to 'crash the stack' if you get stuck in a loop.

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:

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; } }
Both are trivial for this example - and execute in about the same time:
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)
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 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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.