in reply to Iterative vs Recursive Processes
If you do run with mstat, you'll be able to see that there is (unfortunately) still linear growth of memory usage with this version, even though the stack growth is bounded.
Update:#!/usr/bin/perl -w use strict; use Devel::Peek qw(mstat); my $testn = shift || 50; my $result = factorial_iterative($testn); print "goto factorial_iterative($testn) returns $result\n"; sub factorial_iterative { my $n = shift; return fi_helper(1, 1, $n); } sub fi_helper { my ($product, $counter, $max_count) = @_; if ($counter > $max_count) { mstat "return product"; return $product; } else { @_ = ($counter * $product, $counter + 1, $max_count); goto &fi_helper; } }
After thinking about it a while, I was able to prevent any memory growth by getting rid of all arguments to fi_helper and making them "global" variables:
Come to think of it, it has now become an ordinary goto with a little syntactic sugar.#!/usr/bin/perl -w use strict; use Devel::Peek qw(mstat); my $testn = shift || 50; my $result = factorial_iterative($testn); print "goto factorial_iterative($testn) returns $result\n"; my ($product, $counter, $max_count); sub factorial_iterative { my $n = shift; ($product, $counter, $max_count) = (1, 1, $n); return fi_helper(); } sub fi_helper { my $j; if ($counter > $max_count) { mstat "return product"; return $product; } else { ($product, $counter, $max_count) = ($counter * $product, $counter + 1, $max_count); goto &fi_helper; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Iterative vs Recursive Processes
by kelan (Deacon) on May 12, 2003 at 21:40 UTC | |
|
Re: Re: Iterative vs Recursive Processes
by mvaline (Friar) on May 12, 2003 at 17:41 UTC |