in reply to Best way to sum an array?
List::Util (the XS version) beats them all:
Rate recursive recursive2 eval iterative list +util recursive 1244/s -- -4% -68% -97% - +100% recursive2 1297/s 4% -- -67% -97% - +100% eval 3930/s 216% 203% -- -91% +-99% iterative 42708/s 3332% 3192% 987% -- +-85% listutil 281788/s 22544% 21622% 7071% 560% + --
use warnings; use strict; use Benchmark qw/cmpthese/; use List::Util::XS; use List::Util qw/sum/; my @array = 1..1000; my $expect = sum(@array); { use feature 'current_sub'; no warnings 'recursion'; sub SumArryRcs { 1==@_?$_[0]:1>@_?die:shift(@_)+__SUB__->(@_) } sub SumArryRcs2 { @_ ? shift(@_) + __SUB__->(@_) : 0 } } 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 }, eval => sub { eval(join "+", @array) == $expect or die }, listutil => sub { sum(@array) == $expect or die }, });
The recursive approach is not a good solution, as I had to disable warnings on deep recursion and as the array gets longer it really blows up... only for short arrays does it outperform the eval version.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Best way to sum an array?
by LanX (Saint) on May 24, 2017 at 18:14 UTC | |
|
Re^2: Best way to sum an array?
by Anonymous Monk on May 24, 2017 at 15:55 UTC | |
by tobyink (Canon) on May 24, 2017 at 17:12 UTC | |
by BillKSmith (Monsignor) on May 24, 2017 at 17:59 UTC | |
|
Re^2: Best way to sum an array?
by LanX (Saint) on May 25, 2017 at 14:21 UTC |