是否可以加快 PHP 中的递归文件扫描? [英] Is it possible to speed up a recursive file scan in PHP?

查看:43
本文介绍了是否可以加快 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.

这篇关于是否可以加快 PHP 中的递归文件扫描?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆