Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: Why is "for" much slower than "while"?

by FunkyMonk (Canon)
on Jan 15, 2010 at 13:12 UTC ( #817633=note: print w/replies, xml ) Need Help??

in reply to Why is "for" much slower than "while"?

for reads in the entire file, building a list of lines and then iterates over that list. while reads the file one line at a time.

Update: Links fixed. Thanks toolic.

  • Comment on Re: Why is "for" much slower than "while"?

Replies are listed 'Best First'.
Re^2: Why is "for" much slower than "while"?
by gam3 (Curate) on Jan 20, 2010 at 13:59 UTC
    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.
              Rate   for  read while
    for   362612/s    --   -7%  -19%
    read  389496/s    7%    --  -13%
    while 449755/s   24%   15%    --
            Rate   for  read while
    for   4.73/s    --  -17%  -37%
    read  5.73/s   21%    --  -24%
    while 7.55/s   60%   32%    --
             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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://817633]
[Discipulus]: choroba the Tk client print out an educated error message that it cant connect..
[Discipulus]: Can't connect to 80Invalid argument at ..perl5.26.64bit/ perl/vendor/lib/ LWP/Protocol/http. pm line 46, <__ANONIO__> line 34500.
[Corion]: Discipulus: That's weird, but maybe one of the machines is still wonky. I haven't looked :-/

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2017-10-24 10:51 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (288 votes). Check out past polls.