in reply to Re: Best way to sum an array?
in thread Best way to sum an array?
FWIW tailcall with goto &sub
use warnings; use strict; use Benchmark qw/cmpthese/; use List::Util::XS; use List::Util qw/sum/; my @array = 1..2000; my $expect = sum(@array); { use feature 'current_sub'; no warnings 'recursion'; sub SumArryRcs { 1==@_?$_[0]:1>@_?die:shift(@_)+__SUB__->(@_); } sub SumArryRcs2 { @_ ? shift(@_) + __SUB__->(@_) : 0; } } { my $agg = 0; sub SumArryRcs3 { if (@_) { $agg += pop; goto &SumArryRcs3 } else { my $res = $agg; $agg = 0; # reset return $res; } } } # warn $expect; # warn SumArryRcs3(@array); # warn SumArryRcs3(@array); # warn scalar @array; # __END__ cmpthese(-1, { iterative => sub { my $agg = 0; $agg += $_ for @array; $agg == $expect or die; }, recursive => sub { SumArryRcs(@array) == $expect or die }, recursive2 => sub { SumArryRcs2(@array) == $expect or die }, recursive3 => sub { SumArryRcs3(@array) == $expect or die }, eval => sub { eval(join "+", @array) == $expect or die }, listutil => sub { sum(@array) == $expect or die }, } );
it's also 30% faster than normal recursion
Rate recursive recursive2 recursive3 eval iterativ +e listutil recursive 184/s -- -4% -24% -46% -98 +% -100% recursive2 192/s 5% -- -20% -43% -98 +% -100% recursive3 240/s 31% 25% -- -29% -98 +% -100% eval 339/s 84% 76% 41% -- -97 +% -100% iterative 10240/s 5472% 5225% 4159% 2923% - +- -95% listutil 205922/s 111960% 106979% 85548% 60701% 1911 +% --
I had a version which used $_[0] instead of aggregating in a closure, but it destroyed the aliased array and made the cmpthese() impossible.
Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!
|
---|