Nice post to get myself some practice in benchmarking. Here's my try:
#!/usr/bin/perl use Benchmark qw(cmpthese); use List::Util qw(reduce); use Inline 'C'; cmpthese (-5, { 'initial' => sub { my @numbers = (2,3,4,5); my $total = 1; for(@numbers){ $total = ($total * $_); } }, 'listutil' => sub { my @numbers = (2,3,4,5); reduce{ $a*=$b } @numbers; }, 'eval' => sub { my @numbers = (2,3,4,5); eval join "*", @numbers; }, '*=' => sub { my @numbers = (2,3,4,5); my $total=1; $total *= $_ for @numbers; }, 'reducing' => sub { my @numbers = (2,3,4,5); $numbers[0] *= pop @numbers while ( @numbers > 1 ); }, 'inline' => sub { my @numbers = (2,3,4,5); multiply( \@numbers ); } }); __DATA__ __C__ double multiply (SV * terms) { I32 numterms = 0; double res = 1.0; int i; if ((!SvROK(terms)) || (SvTYPE(SvRV(terms)) != SVt_PVAV) || ((numterms = av_len((AV *)SvRV(terms))) < 0)) { return 0; } for (i = 0; i <= numterms; i++) { res *= SvNV(* av_fetch((AV *)SvRV(terms), i, 0)); } return res; }
the results:
Rate eval reducing initial *= listutil inline eval 21683/s -- -84% -84% -85% -85% -89% reducing 134819/s 522% -- -4% -6% -7% -31% initial 139854/s 545% 4% -- -3% -4% -28% *= 144019/s 564% 7% 3% -- -1% -26% listutil 145100/s 569% 8% 4% 1% -- -25% inline 194405/s 797% 44% 39% 35% 34% --
If I'm doing something wrong here, please correct me.

In reply to Re: Multiplying together the numers in an array by eXile
in thread Multiplying together the numers in an array by Cody Pendant

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.