问题
Which is faster between glob() and opendir(), for reading around 1-2K file(s)?
回答1:
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.
回答2:
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:
- http://www.phparch.com/2010/04/28/putting-glob-to-the-test/
回答3:
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.
回答4:
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
回答5:
Okay,
Long story short:
- if you want full filenames+paths, sorted, glob is practically unbeatable.
- if you want full filenames+paths unsorted, use glob with GLOB_NOSORT.
- if you want only the names, and no sorting, use opendir + loop.
That's it.
Some more thoughts:
You can do tests to compose the exact same result with different methods only to find they have approximately the same time cost. Merely for fetching the information you'll have no real winner. However, consider these:
Dealing with a huge file list, glob will sort faster - it uses the filesystem's sort method which will always be superior. (It knows what it sorts while PHP doesn't, PHP sorts a hashed array of arbitrary strings, it's simply not fair to compare them.)
You'll probably want to filter your list by some extensions or filename masks for which glob is really efficient. You have fnmatch() of course, but calling it every time will never be faster than a system-level filter trained for this very job.
On the other hand, glob returns a significantly bigger amount of text (each name with full path) so with a lot of files you may run into memory allocation limits. For a zillion files, glob is not your friend.
来源:https://stackoverflow.com/questions/2763290/which-is-faster-glob-or-opendir