Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
I don't think this is the complete answer as
read $IN1, my $buffer, -s $IN1; ++$counts{$_} for split( /^/m, $buffer );
is faster than the for.
/dev/null
          Rate   for  read while
for   362612/s    --   -7%  -19%
read  389496/s    7%    --  -13%
while 449755/s   24%   15%    --

/usr/share/dict/words
        Rate   for  read while
for   4.73/s    --  -17%  -37%
read  5.73/s   21%    --  -24%
while 7.55/s   60%   32%    --

/etc/passwd
         Rate   for while  read
for   14434/s    --  -17%  -21%
while 17297/s   20%    --   -6%
read  18355/s   27%    6%    --
#!/usr/bin/perl use strict; use Benchmark qw( cmpthese ); foreach my $file qw ( /dev/null /usr/share/dict/words /etc/passwd ) { open my $IN1, '<', $file or die "could not open $file"; my @list = <$IN1>; seek( $IN1, 0, 0 ); print "$file\n"; cmpthese( -5, { for => sub { seek( $IN1, 0, 0 ); my %counts = (); ++$counts{$_} for <$IN1>; die unless keys %counts == @list; }, while => sub { seek( $IN1, 0, 0 ); my %counts = (); ++$counts{$_} while <$IN1>; die unless keys %counts == @list; }, read => sub { seek( $IN1, 0, 0 ); my %counts = (); read $IN1, my $buffer, -s $IN1; ++$counts{$_} for split( /^/m, $buffer ); die unless keys %counts == @list; }, } ); }
-- gam3
A picture is worth a thousand words, but takes 200K.

In reply to Re^2: Why is "for" much slower than "while"? by gam3
in thread Why is "for" much slower than "while"? by di

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 sharing their wisdom with the Monastery: (3)
As of 2024-04-20 04:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found