if I write a recursive procedure like factorial_iterative ... does it's memory usage grow linearly the way factorial_recursive looks like it should.
Yep, since it's just a wrapper around a recursive sub, fi_helper. Recursion isn't terribly efficient in perl since function calls aren't too swift and take up a fair bit of memory (hence the recusion warning (see. perldiag)). An iterative approach however will be a bit quicker e.g
use strict; use Benchmark 'cmpthese'; my $limit = @ARGV ? shift : 100; cmpthese(-10, { recurse => sub { rec($limit) }, iterate => sub { itr($limit) }, }); sub rec { my $n = shift; return $n == 1 ? return 1 : $n * rec($n - 1); } sub itr { my($n, $r) = (shift, 1); $r *= $n-- while $n > 1; return $r; } __output__ Benchmark: running iterate, recurse for at least 10 CPU seconds... iterate: 11 wallclock secs (10.58 usr + 0.00 sys = 10.58 CPU) @ 58 +14.45/s (n=61546) recurse: 11 wallclock secs (10.23 usr + 0.00 sys = 10.23 CPU) @ 16 +77.45/s (n=17162) Rate recurse iterate recurse 1677/s -- -71% iterate 5814/s 247% --
Of course all benchmarks are to be taken with a grain of salt, but I think this gives a pretty clear illustration of the hit recursion incurs.
HTH

_________
broquaint


In reply to Re: Re: Re: Iterative vs Recursive Processes by broquaint
in thread Iterative vs Recursive Processes by mvaline

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.