是否可以加快 PHP 中的递归文件扫描?

2022-01-24 00:00:00 递归 performance iteration find php

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

I've been trying to replicate Gnu Find ("find .") in PHP, but it seems impossible to get even close to its speed. The PHP implementations use at least twice the time of Find. Are there faster ways of doing this with PHP?

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

I added a code example using the SPL implementation -- its performance is equal to the iterative approach

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

When calling find from PHP it was actually slower than the native PHP implementation. I guess I should be satisfied with what I've got :)

// 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
";
      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
";        
        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);
}

推荐答案

PHP 的执行速度不如 C,简单明了.

PHP just cannot perform as fast as C, plain and simple.

相关文章