views:

238

answers:

4

Which is faster between glob() and opendir(), for reading around 1-2K file(s)?

+1  A: 

Not sure whether that is perfect comparison but glob() allows you to incorporate the shell-like patterns as well where as opendir is directly there for the directories there by making it faster.

Sarfraz
`glob()` uses shell-like patterns, not regular expressions
kemp
@kemp: added those details in my answer, thanks
Sarfraz
+3  A: 

http://code2design.com/forums/glob_vs_opendir

Obviously opendir should be (and is) quicker as it opens the directory handler and lets you iterate. Because glob() has to parse the first argument it's going to take some more time (plus glob handles recursive directories so it'll scan subdirs, which will add to the execution time.

Ben Rowe
A: 

another question that can be answered with a bit of testing. i had a convenient folder with 412 things in it, but the results shouldn't vary much, i imagine:

igor47@whisker ~/test $ ls /media/music | wc -l
412
igor47@whisker ~/test $ time php opendir.php 
414 files total

real    0m0.023s
user    0m0.000s
sys 0m0.020s
igor47@whisker ~/test $ time php glob.php 
411 files total

real    0m0.023s
user    0m0.010s
sys 0m0.010s
Igor
+3  A: 

glob and opendir do different things. glob finds pathnames matching a pattern and returns these in an array, while opendir returns a directory handle only. To get the same results as with glob you have to call additional functions, which you have to take into account when benchmarking, especially if this includes pattern matching.

Bill Karwin has written an article about this recently. See:

Gordon