in reply to Re: Things every perl programmer should know? (faster?)
in thread Things every perl programmer should know?
What I, as a Perl programmer, would like to know, is some estimate of how much slower glob is than readdir. How about some numbers based on what you saw as one source of data? You said over 4000 files and show the contents of the files being read. How long did the different versions take? About how large were the files you were reading?
I was curious myself, so I created a directory with 10000 files (zero size), half of them with the extension ".tmp".
I wrote equivalent readdir and glob statements to get all of the *.tmp files, and the glob is noticeably slower. It takes about 3 seconds while the readdir with grep seems instantaneous. This is just a rough eyeball benchmark, but still, the glob is definitely slower. I even switched the order of the directory reads, and got the same result. Here is the code (this was run on an old AIX system):
I'd say if the 3 seconds doesn't matter, I'd do it with glob to save myself the coding. If this were embedded in a library that I expected other people to use, I'd do it with readdir 'just in case' speed matters.
my @file2 = glob("tmp/*.tmp");
my $count2 = @file2;
opendir(DIR, "tmp") or die "Acck: $!";
my @file1 = grep /\.tmp$/, readdir DIR;
my $count1 = @file1;
Update:This was perl 5.6.1 (and I received the same results with File::Glob::bsd_glob and the GLOB_NOSORT option).
Another update: I vaguely remember glob being painfully slow on Windows at one time, which has since been fixed (I think). And it may have been only with the angle bracket syntax...can anyone confirm?