【问题标题】:file_exists() versus in_array() of scandir() -- which is faster? [closed]file_exists() 与 scandir() 的 in_array() ——哪个更快? [关闭]
【发布时间】:2013-01-09 03:59:03
【问题描述】:

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

foreach($entries as $entry){ // let's say this loops 1000 times
   if (file_exists('/some/dir/'.$entry.'.jpg')){
      echo 'file exists';
   }
}

我假设这必须访问硬盘 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()子目录放入数组中,以便我可以用这种方法比较文件是否存在?

【问题讨论】:

  • 我假设这必须访问硬盘 1000 次并检查每个文件是否存在。 -> 如果您没有缓存...
  • file_exists() 被称为相当慢。但是你到底想开发什么?大多数时候这不是速度问题,而是编码错误。
  • 您可以通过先使用array_flip() 然后使用isset() 来加速in_array()
  • 您的问题没有明确的答案;您需要多次扫描文件夹吗?缓存它仍然重要吗? $entries 是如何填充的?等

标签: php


【解决方案1】:

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

【讨论】:

  • 并使用 memory_get_usage 获取内存量(以字节为单位)。
  • @likai 是的,这也可能有用+1,我会修改我的答案
【解决方案2】:

你可以看看here

我修改了“问题代码”之类的,你可以做一个快速检查,

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

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

【讨论】:

    猜你喜欢
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多