We avoid the use of globals because:
I decided to explore the other options a bit, and it appears that globals and lexicals are almost identical in performance and closure performance is only slightly slower.
Here is the test code and its results:
and the results#!/usr/bin/perl -w use strict; use Benchmark qw/:all/; my $iGlobal; my $x = 4; timethese (1000000, { 'Recursion' => 'Rfactorial(30)', 'Global' => 'Gfactorial(30)', 'Lexical' => 'Lfactorial(30)', 'Closure' => '&{Cfactorial()}(30)', } ); # A classic, recursive soulution. sub Rfactorial { my $i = shift; return 1 if $i == 0; return 1 if $i == 1; return $i * Rfactorial($i - 1); } # Rewritten to use global variables. sub Gfactorial { $iGlobal = shift; return 1 unless $iGlobal > 1; my $result = 1; while ($iGlobal > 1) { $result = $result * $iGlobal; $iGlobal--; } return $result; } # expressed with lexicals sub Lfactorial { my $iLexical = shift; return 1 unless $iLexical > 1; my $result = 1; while ($iLexical > 1) { $result = $result * $iLexical; $iLexical--; } return $result; } # Rewritten to use closures sub Cfactorial { my $iClosure; return sub { my $iClosure = shift; my $result = 1; while ($iClosure > 1) { $result = $result * $iClosure; $iClosure --; } return $result; } }
Benchmark: timing 1000000 iterations of Closure, Global, Lexical, Recu +rsion... Closure: 66 wallclock secs (61.70 usr + 0.00 sys = 61.70 CPU) @ 16 +207.46/s (n=1000000) Global: 62 wallclock secs (58.39 usr + 0.00 sys = 58.39 CPU) @ 17 +126.22/s (n=1000000) Lexical: 63 wallclock secs (58.55 usr + 0.00 sys = 58.55 CPU) @ 17 +079.42/s (n=1000000) Recursion: 208 wallclock secs (176.95 usr + 0.00 sys = 176.95 CPU) @ + 5651.31/s (n=1000000)
Do the other monks have more insight?
update (broquaint): changed <pre> tags to <code> tags around the Benchmark result
Edit by tye, add READMORE
In reply to Recursion Alternatives? by Cabrion
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |