This node was inspired by Re^2: file reading issues.

I recently ran a simple test of the speed of these two blocks of code:
open(FILE,"<$file") || die $!; read FILE, my $data, -s $file; close(FILE);
open(FILE,"<$file") || die $!; my $data = do { local $/; <FILE> }; close(FILE);
I expected the second method (a traditional slurp) to be faster. However, I was surprised to find that the read function was almost twice as fast!

Can anyone explain why?

Here's the simple test I ran:
#!/usr/bin/perl use strict; use warnings; use Time::HiRes qw(time); $| = 1; my $file = '/path/to/file.pdf'; my $numtests = 1000; print "using read function\n"; for (my $x = 0; $x < 6; $x++) { my $start = time(); for (my $i = 0; $i <= $numtests; $i++) { open(FILE,"<$file") || die $!; read FILE, my $data, -s $file; close(FILE); } my $end = time(); print $end - $start,"\n"; } print "\ntradtional slurp\n"; for (my $x = 0; $x < 6; $x++) { my $start = time(); for (my $i = 0; $i <= $numtests; $i++) { open(FILE,"<$file") || die $!; my $data = do { local $/; <FILE> }; close(FILE); } my $end = time(); print $end - $start,"\n"; } # exit; #<- removed for blazar ;)

Here's the output:
using read function 0.612063884735107 0.62070107460022 0.599463939666748 0.60235595703125 0.610018014907837 0.603386878967285 tradtional slurp 1.03461217880249 1.0298318862915 1.05549097061157 1.08192896842957 1.02464509010315 1.0180230140686

In reply to Speed reading (files) by kwaping

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.