file_exists()与scandir()的in_array() - 哪个更快?

时间:2013-01-25 07:51:02

标签: php

假设我们有一个这样的循环:

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()子目录进入数组,这样我可以使用这种方法比较存在的文件吗?

2 个答案:

答案 0 :(得分:5)

我的意见是,我相信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

答案 1 :(得分:0)

您可以查看here

我修改了“问题代码”,例如,你可以快速检查,

<?php
   $start = microtime();
    //Your code
    $end = microtime();
    $result= $now-$then;
    echo $result;
?>

我个人认为scandir()会比in_array()更快。