vagabonding electron,
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:
#! perl
use strict;
use warnings;
use Benchmark qw( cmpthese );
my $n = 1e6;
my $foreach_loop_total = 0;
my $c_for_loop_total = 0;
cmpthese
(
1000,
{
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";
sub foreach_loop
{
$foreach_loop_total += -$_ for -$n .. 0;
}
sub c_for_loop
{
for (my $j = $n; $j >= 0; --$j)
{
$c_for_loop_total += $j;
}
}
Output:
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
12:05 >
So, it appears that the overhead of the additional negation outweighs the benefit of not having to create a new scope on each iteration.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|