Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

comment on

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

Many of us know that foreach (@array) {...} is optimized - no extra copying, just some iterations over array. But it was not obvious for me whether or not more complex constructs are optimized this way.
In such cases they better be written as: for ($i=0;$i<=$#array;$i++) {...}

So I wrote simple benchmark program and found out that optimizations which perl performs are quite good:

use strict; use Benchmark; my ($x,$i); my @f = ('a'..'zz'); my $f = \@f; sub first_one { for (@f) {$x++} } sub second_one { for (@$f) {$x++} } sub third_one { for ('a'..'zz') {$x++} } sub fourth_one { for ($i=0;$i<=$#f;$i++) {$x++} } timethese(10_000, { 'first' => \&first_one, 'second' => \&second_one, 'third' => \&third_one, 'fourth' => \&fourth_one, });
result:
Benchmark: timing 10000 iterations of first, fourth, second, third... first: 6 wallclock secs ( 6.02 usr + 0.00 sys = 6.02 CPU) @ 16 +61.68/s (n=10000) fourth: 12 wallclock secs (11.98 usr + 0.00 sys = 11.98 CPU) @ 83 +4.86/s (n=10000) second: 7 wallclock secs ( 6.00 usr + 0.00 sys = 6.00 CPU) @ 16 +67.22/s (n=10000) third: 9 wallclock secs ( 9.57 usr + 0.00 sys = 9.57 CPU) @ 10 +44.50/s (n=10000)
So, I was here to share this knowledge.

In reply to Is for(@$array_ref) construct optimized? YES! by Weasel

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 studying the Monastery: (5)
As of 2024-04-19 14:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found