You are correct that a foreach loop is faster than a C-style for loop, other things being equal. As BrowserUk has explained, this is because with the latter, but not the former,
you must always pay the penalty of creating a new scope for each iteration of the loop.
But my point was that if you count upwards from -$n, you add the overhead of a unary negation operator when you come to actually use the original $n:
use Benchmark qw( cmpthese );
my $n = 1e6;
my $foreach_loop_total = 0;
my $c_for_loop_total = 0;
foreach_loop => \&foreach_loop,
c_for_loop => \&c_for_loop,
print "\$foreach_loop_total = $foreach_loop_total\n";
print "\$c_for_loop_total = $c_for_loop_total\n";
$foreach_loop_total += -$_ for -$n .. 0;
for (my $j = $n; $j >= 0; --$j)
$c_for_loop_total += $j;
12:00 >perl 555_SoPW.pl
Rate foreach_loop c_for_loop
foreach_loop 5.62/s -- -8%
c_for_loop 6.13/s 9% --
$foreach_loop_total = 500000500000000
$c_for_loop_total = 500000500000000
So, it appears that the overhead of the additional negation outweighs the benefit of not having to create a new scope on each iteration.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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:
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||