假设我们有一个这样的循环:
foreach($entries as $entry){ // let's say this loops 1000 times
if (file_exists('/some/dir/'.$entry.'.jpg')){
echo 'file exists';
}
}
我假设这必须访问HDD 1000次并检查每个文件是否存在.
这样做呢?
$files = scandir('/some/dir/');
foreach($entries as $entry){ // let's say this loops 1000 times
if (in_array($entry.'.jpg', $files)){
echo 'file exists';
}
}
问题1:如果这次访问硬盘一次,那么我相信它应该快得多.我是对的吗?
但是,如果我必须检查文件的子目录,如下所示:
foreach($entries as $entry){ // let's say this loops 1000 times
if (file_exists('/some/dir/'.$entry['id'].'/'.$entry['name'].'.jpg')){
echo 'file exists';
}
}
问题2:如果我想应用上述技术(数组中的文件)来检查条目是否存在,我怎样才能将scandir()子目录放入数组中,以便我可以使用这种方法比较文件是否存在?
解决方法:
我认为,我相信scandir()会更快,因为它只读取一次目录,另外file_exists()已知非常慢.
此外,您可以使用glob().这将列出目录中与特定模式匹配的所有文件.见here
无论我的意见如何,你都可以像这样运行一个简单的脚本来测试速度:
<?PHP
// Get the start time
$time_start = microtime(true);
// Do the glob() method here
// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;
echo '\'glob()\' finished in ' . $time . 'seconds';
// Do the file_exists() method here
// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;
echo '\'file_exists()\' finished in ' . $time . 'seconds';
// Do the scandir() method here
// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;
echo '\'scandir()\' finished in ' . $time . 'seconds';
?>
不确定上述脚本如何使用缓存,您可能必须将测试分成单独的文件并单独运行
更新1
您还可以实现函数memory_get_usage()以返回当前分配给PHP脚本的内存量.你可能会觉得这很有用.有关详细信息,请参见here.
更新2
至于第二个问题,有几种方法可以列出目录中的所有文件,包括子目录.看看这个问题的答案:
Scan files in a directory and sub-directory and store their path in array using php