in reply to Recursion Alternatives?

Have you thought about caching the answers? Trade RAM for speed. The easiest way to do this is to use Memoize; I added a memoizing recursive sub (#1) and a memoizing iterative sub (#2), then benchmarked it again - this time using cmpthese. Here is the sub and the results. I left off the recursive sub.

# caching previous answers use Memoize; memoize('Mfactorial'); memoize('Mfactorial2'); sub Mfactorial { my $num = shift; return 1 if $num == 0 or $num == 1; return $num * Mfactorial($num - 1); } sub Mfactorial2 { my $iLex = shift; return 1 unless $iLex > 1; my $result =1; while ($iLex > 1) { $result = $result * $iLex; $iLex--; } $result; } __DATA__ results: Benchmark: timing 1000000 iterations of Closure, Global, Lexical, Memo +, Memo2... Closure: 25 wallclock secs (26.29 usr + 0.00 sys = 26.29 CPU) @ 38 +037.28/s (n=1000000) Global: 26 wallclock secs (26.41 usr + 0.00 sys = 26.41 CPU) @ 37 +864.45/s (n=1000000) Lexical: 28 wallclock secs (25.32 usr + 0.05 sys = 25.37 CPU) @ 39 +416.63/s (n=1000000) Memo: 16 wallclock secs (16.20 usr + 0.02 sys = 16.22 CPU) @ 61 +652.28/s (n=1000000) Memo2: 17 wallclock secs (16.13 usr + 0.03 sys = 16.16 CPU) @ 61 +881.19/s (n=1000000) Rate Global Closure Lexical Memo Memo2 Global 37864/s -- -0% -4% -39% -39% Closure 38037/s 0% -- -3% -38% -39% Lexical 39417/s 4% 4% -- -36% -36% Memo 61652/s 63% 62% 56% -- -0% Memo2 61881/s 63% 63% 57% 0% --

Recursion looks pretty good after this! Now, I don't know if your actual application would benefit from caching the results. We're looking at the classic recursive algorithm here, so YMMV.

If you want to duplicate this, be sure to call memoize before you benchmark.