Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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.

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re^3: counting backward by Athanasius
in thread counting backward by ag4ve

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



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-25 07:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found