I have a FileSystemIterator which I need to sort.
I use uaSort function on iterator_to_array(new FileSystemIterator($dir, FilesystemIterator::SKIP_DOTS))
with following sorting function:
function nameSort($a, $b) {
if($a->isDir() === $b->isDir()){
return strNatCaseCmp($a->getFilename(), $b->getFilename());
}
return $a->isDir() ? -1 : 1;
}
I have 1063 files and directories in $dir and nameSort gets called 11369-times the list of files is generated in average time of around 6 seconds. I thought additional testing whether item is directory made uaSort to call nameSort more times but this assumption was wrong because when I removed the lines with isDir number of calls raised to 11957. The time it took to run however dropped to 0.6 second.
It looks like calling isDir is very slow (it makes the list 10 times slower). How can I speed this up?
If calling isDir
is so costly, and you are calling it multiple times per path, you might want to cache if something is a dir, and retrieve it from the cache first. This can safe a lot of calls to the isDir
method.
if you are trying to get just the contents of a single directory you could use glob.
$file = glob($path."/*", GLOB_MARK);
should already be sorted and directories can be identified by tailing / so you can array_filter those out