php - 是否可以在 PHP 中加速递归文件扫描?

标签 php performance recursion find iteration

我一直在尝试复制 Gnu Find ("find .") 在 PHP 中,但似乎不可能接近它的速度。 PHP 实现使用的时间至少是 Find 的两倍。有没有用 PHP 更快的方法?

编辑:我添加了一个使用 SPL 实现的代码示例——它的性能等同于迭代方法

EDIT2:当从 PHP 调用 find 时,它实际上比本地 PHP 实现慢。我想我应该对我所拥有的感到满意:)

// measured to 317% of gnu find's speed when run directly from a shell
function list_recursive($dir) { 
  if ($dh = opendir($dir)) {
    while (false !== ($entry = readdir($dh))) {
      if ($entry == '.' || $entry == '..') continue;

      $path = "$dir/$entry";
      echo "$path\n";
      if (is_dir($path)) list_recursive($path);       
    }
    closedir($d);
  }
}

// measured to 315% of gnu find's speed when run directly from a shell
function list_iterative($from) {
  $dirs = array($from);  
  while (NULL !== ($dir = array_pop($dirs))) {  
    if ($dh = opendir($dir)) {    
      while (false !== ($entry = readdir($dh))) {      
        if ($entry == '.' || $entry == '..') continue;        

        $path = "$dir/$entry";        
        echo "$path\n";        
        if (is_dir($path)) $dirs[] = $path;        
      }      
      closedir($dh);      
    }    
  }  
}

// measured to 315% of gnu find's speed when run directly from a shell
function list_recursivedirectoryiterator($path) {
  $it = new RecursiveDirectoryIterator($path);
  foreach ($it as $file) {
    if ($file->isDot()) continue;

    echo $file->getPathname();
  }
}

// measured to 390% of gnu find's speed when run directly from a shell
function list_gnufind($dir) { 
  $dir = escapeshellcmd($dir);
  $h = popen("/usr/bin/find $dir", "r");
  while ('' != ($s = fread($h, 2048))) {
    echo $s;
  }
  pclose($h);
}

最佳答案

我不确定性能是否更好,但您可以使用递归目录迭代器来简化代码...请参阅 RecursiveDirectoryIterator'SplFileInfo` .

$it = new RecursiveDirectoryIterator($from);
foreach ($it as $file)
{
    if ($file->isDot())
        continue;

    echo $file->getPathname();
}

关于php - 是否可以在 PHP 中加速递归文件扫描?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/624120/

相关文章:

php - 如何在PHP代码中的file_get_contents前面添加域

c# - 软件更新版本的应用散列

php - Laravel/Eloquent 中按多个条件过滤模型

python - 如何加快Python代码在功能强大的计算机上运行的速度?

performance - 经典单例 vs. Java 8 性能懒惰

algorithm - 理解递归/子问题如何组合(最大子数组算法)

php - HTML/PHP Post方法到不同的服务器

java - 这个小小的错别字会产生什么样的影响呢?

c++ - 将递归函数转换为尾递归函数

java - 字符串的无效递归反转方法