I have a folder structure with something over 300.000 files and folders in it.
When I iterate over this structure to get all files of a certain type, this take about half a second to complete:
$path = "/path/to/folder";
$folder = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($folder);
$files = new RegexIterator($iterator, '/^.+\.jpg$/i', RecursiveRegexIterator::GET_MATCH);
But getting the length of the resulting iterator ($files) takes about ten seconds:
$n = iterator_count($files);
Is there a faster way to get the number of items in the iterator? Maybe during iteration?
These all take around 10 seconds, too:
1. find (commandline)
find /path/to/folder -type f | wc -l
2. scandir (PHP, source)
$intFileCount = countFilesInDirectory($path, array('jpg'));
echo $intFileCount;
function countFilesInDirectory($strPathToDirectory, $arrExtensions) {
$intFileCount = 0;
$arrFiles = scandir($strPathToDirectory);
foreach($arrFiles as $strFile) {
if('.' != $strFile && '..' != $strFile) {
if(is_dir("$strPathToDirectory/$strFile") && is_readable("$strPathToDirectory/$strFile")) {
$intFileCount += countFilesInDirectory("$strPathToDirectory/$strFile", $arrExtensions);
} else {
$arrFileInfo = pathinfo($strFile);
if(in_array($arrFileInfo['extension'], $arrExtensions)) {
$intFileCount += 1;
}
}
}
}
return $intFileCount;
}
Note:
I'm counting the seconds in my head. So there might be some slight difference between methods, but it is not so large as to be relevant to me.