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; } }
In reply to Re: Iterative vs Recursive Processes
by Thelonius
in thread Iterative vs Recursive Processes
by mvaline
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |