it should run a lot faster/be more efficient than the latter

While recursion may make for much simpler code, it will not necessarily make for faster/more efficient code tail recursion is better in this regard. A classic example is calculation of factorials. In my, doubtless horrid, example:

#!perl use strict; use warnings; use diagnostics; use Benchmark qw(:all); #print 'looping: ' . looping(10) . "\n"; #print 'recursive: ' . recursive(10) . "\n"; my $count = -5; cmpthese($count,{ recursive => sub{&recursive(50)}, looping => sub{&looping(50)}}); sub recursive { my $x = shift; if($x <= 1) { return 1; } else{ return $x * recursive($x - 1); } } sub looping { my $x = shift; my $y = 1; foreach my $z (1 .. $x) { $y*=$z; } return $y; }

I got these results:

Rate recursive looping recursive 9228/s -- -77% looping 39979/s 333% --

Which, if I interpret it correctly, shows the looping sub is quite a bit faster.

Of course, this does not mean that all recursive routines that can be replaced by iterative routines should be; this is likely to be misplaced optimization. There are a great number of cases where the code written with recursion is going to be much simpler, which means that it will globally be better: more reliable, easier to test, easier to understand, quicker to get right.

emc

At that time [1909] the chief engineer was almost always the chief test pilot as well. That had the fortunate result of eliminating poor engineering early in aviation.

—Igor Sikorsky, reported in AOPA Pilot magazine February 2003.

In reply to Re: Misunderstanding Recursion by swampyankee
in thread Misunderstanding Recursion by Andrew_Levenson

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.