1.2.75. Avoid glob() Usage¶
glob() and scandir() sorts results by default. When that kind of sorting is not needed, save some time by requesting NOSORT
with those functions.
Besides, whenever possible, use scandir() instead of glob(). Using opendir() and a while loop may be even faster.
This analysis skips scandir() and glob() if they are explicitly configured with flags (aka, sorting is explicitly needed).
glob() accepts wildchar, such as *
, that may not easily replaced with scandir() or opendir().
<?php
// Scandir without sorting is the fastest.
scandir('docs/', SCANDIR_SORT_NONE);
// Scandir sorts files by default. Same as above, but with sorting
scandir('docs/');
// glob sorts files by default. Same as below, but no sorting
glob('docs/*', GLOB_NOSORT);
// glob sorts files by default. This is the slowest version
glob('docs/*');
?>
See also Putting glob to the test, How to list files recursively in a directory with PHP iterators and glob://.
1.2.75.1. Connex PHP features¶
1.2.75.1.1. Suggestions¶
Use
FilesystemIterator
orDirectoryIterator
classes.Use
RegexIterator
to filter any unwanted results fromFilesystemIterator
.Use
glob
protocol for files : $it = new DirectoryIterator(‘glob://path/to/examples/*.php’);
1.2.75.1.2. Specs¶
Short name |
Performances/NoGlob |
Rulesets |
|
Exakat since |
0.9.6 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Examples |
|
Available in |