in reply to Tail Recursion "Optimising" with goto &sub

Here's a quickie benchmark, run on perl5.8.0, Athlon XP 1800 linux box with 256MB of memory:

Benchmark: timing 10000 iterations of goto, iterative, regular... goto: 19 wallclock secs (18.92 usr + 0.00 sys = 18.92 CPU) @ 52 +8.54/s (n=10000) iterative: 6 wallclock secs ( 6.23 usr + 0.00 sys = 6.23 CPU) @ 16 +05.14/s (n=10000) regular: 23 wallclock secs (22.94 usr + 0.00 sys = 22.94 CPU) @ 43 +5.92/s (n=10000) Rate regular goto iterative regular 436/s -- -18% -73% goto 529/s 21% -- -67% iterative 1605/s 268% 204% --

...And here's the code. My apologies if I made mistakes, I didn't spend that much time on this ;)

use strict; use Benchmark qw/ cmpthese /; cmpthese( 10000, { regular => sub{ regrecurse($_) for ( map{10*$_} (1..10) ) }, goto => sub{ gotorecurse($_) for ( map{10*$_} (1..10) ) }, iterative => sub{ iterative($_) for ( map{ 10* $_ } (1..10) ) +} }, ); sub iterative { my $n = shift; my $m = 1; for(1..$n) { $m *= $_; } return $m; } sub regrecurse { my $n = shift; _reghelp(1, $n); } sub _reghelp { my($n, $m) = @_; if($m <= 1) { return $n; } return _reghelp($n * $m, $m - 1); } sub gotorecurse { my $n = shift; @_ = (1, $n); goto &_gotohelp; } sub _gotohelp { if($_[1] <= 1) { return $_[0]; } $_[0] *= $_[1]; $_[1]--; goto &_gotohelp; }