I think your results are so surprising because your benchmark code adds a lot of unneccessary cruft to the different approaches. For example, in method 1 you're instantiating my $file at every pass through the loop.
FWIW, here's my benchmark of approach 1 (iterative) vs. approach 3 (slurpy):
use Benchmark qw/:all/;
my $folder = "C:\\Perl";
sub iterative {
opendir $DIR, '.';
my $file;
while ($file = readdir $DIR) {
$file = "$folder\\$file";
next unless -f $file;
my @s = stat $file;
}
closedir $DIR; # I like being explicit;
}
sub slurpy {
opendir $DIR, '.';
my @files = map { "$folder\\$_" } grep { -f $_ } readdir($DIR);
foreach (@files) {
my @s = stat $_;
}
closedir $DIR;
}
cmpthese ( 200, {
'iterative' => \&iterative,
'slurpy' => \&slurpy,
});
__END__
Rate slurpy iterative
slurpy 74.4/s -- -44%
iterative 133/s 79% --
As you can see, the iterative approach is *much* faster in my benchmark. (The other variable is that I'm running WinXP).
I have similar results on OSX (FreeBSD-based "Darwin"), see below.
C:\>perl -v
This is perl, v5.8.6 built for MSWin32-x86-multi-thread
(with 3 registered patches, see perl -V for more detail)
My test on my home OSX machine:
Rate slurpy iterative
slurpy 1264/s -- -17%
iterative 1517/s 20% --
$ perl -v
This is perl, v5.8.6 built for darwin-thread-multi-2level
(with 2 registered patches, see perl -V for more detail)
Updates:
- 2005-01.Jan-17 : OSX info added
-
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.