Just for fun, I wanted to measure the speed difference of greping and just using while.
So I created, in a test directory, lots of small files :
$dir = "test";
mkdir $dir or die "Unable to create dir : $!" if not ( -d "$dir");
chdir $dir;
foreach ( 'aaa' .. 'zzz' ) {
open F, "> $_";
my $data = chr(97 + int rand 10);
print F $data;
close F;
}
Then I tried to list each file of this directory, and compare :</o>
use Benchmark qw/cmpthese/;
$dir = "test";
opendir DIR, "< $dir";
cmpthese(1000, {
'grep' => sub {
opendir DIR, "$dir" or die "Unable to open dir : $!\n";
@list=grep(!/^(\.+?)$/,readdir(DIR));
closedir DIR;
},
'while' => sub {
opendir DIR, "$dir" or die "Unable to open dir : $!\n";
while (readdir(DIR)) {
push @list, $_ unless /^(\.+?)$/;
closedir DIR;
}
}
});
As expected, the difference is huge :
D:\Perl\bin>perl test2.pl
Rate grep while
grep 6.51/s -- -100%
while 2667/s 40833% --
D:\Perl\bin>
Using grep, perl interprets readdir in list context, and builds and return the whole list of files of the directory, that is huge.
When using while, perl returnes file names each by each, which is much cheaper in memory.
So, in your case : use while.
For information, I was using Windows XP SP1 and ActivePerl 5.8.4 on a NTFS file system.
HTH
|