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.


In reply to Re: Best way to sum an array? by haukex
in thread Best way to sum an array? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.