【问题标题】:php recursive folder readdir vs find performancephp递归文件夹readdir vs查找性能
【发布时间】:2012-01-09 08:16:29
【问题描述】:

我遇到了几篇关于性能和 readdir 的文章 这是php脚本:

function getDirectory( $path = '.', $level = 0 ) { 
    $ignore = array( 'cgi-bin', '.', '..' );
    $dh = @opendir( $path );
    while( false !== ( $file = readdir( $dh ) ) ){
        if( !in_array( $file, $ignore ) ){
            $spaces = str_repeat( ' ', ( $level * 4 ) );
            if( is_dir( "$path/$file" ) ){
                echo "$spaces $file\n";
                getDirectory( "$path/$file", ($level+1) );
            } else {
                echo "$spaces $file\n";
            }
        }
    }
    closedir( $dh );
}
getDirectory( "." );  

这会正确地回显文件/文件夹。

现在我发现了这个:

$t = system('find');
print_r($t);

它还可以找到所有文件夹和文件,然后我可以像第一个代码一样创建一个数组。

我认为system('find');readdir 快​​,但我想知道这是否是一个好习惯? 非常感谢

【问题讨论】:

  • 系统调用肯定是不可移植的。您的示例代码依赖于 *nix 操作系统。
  • 我有 apache 和 php+mysql 的 centos 5 可以吗?
  • 习惯使用system() 调用也是一个坏主意。没有参数它们应该没问题,但如果你根据用户输入动态构造它们,你可能会造成严重的安全漏洞。
  • @Inerdial 哦,我没想到,谢谢

标签: php find system readdir


【解决方案1】:

这是我在我的服务器上使用一个简单的 for 循环进行 10 次迭代的基准测试:

$path = '/home/clad/benchmark/';
// this folder has 10 main directories and each folder as 220 files in each from 1kn to 1mb

// glob no_sort = 0.004 seconds but NO recursion
$files = glob($path . '/*', GLOB_NOSORT);

// 1.8 seconds - not recommended
exec('find ' . $path, $t);
unset($t);

// 0.003 seconds
if ($handle = opendir('.')) {
 while (false !== ($file = readdir($handle))) {
  if ($file != "." && $file != "..") {
   // action
  }
 }
 closedir($handle);
}

// 1.1 seconds to execute
$path = realpath($path);
$objects = new RecursiveIteratorIterator(
 new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
  foreach($objects as $name => $object) {
   // action
  }
}

如果您的网站有大量流量,显然 readdir 使用起来会更快。

【讨论】:

  • 很好的答案,但我是否遗漏了什么...... readdir() 解决方案本身不是递归的。这不会扭曲结果吗?
  • 如何对像你这样的单个函数进行基准测试,aki?
【解决方案2】:

'find' 不可移植,它是一个 unix/linux 命令。 readdir() 是可移植的,可以在 Windows 或任何其他操作系统上运行。此外,不带任何参数的 'find' 是递归的,所以如果你在一个有很多子目录和文件的目录中,你会看到所有这些,而不仅仅是那个 $path 的内容。

【讨论】:

  • 虽然我看到你的函数也是递归的,所以忽略关于递归的咆哮。但请注意,“find”的输出也以一种特殊的方式格式化。
  • 我从来没有用过windows,所以它只是unix或linux,我可以处理格式
  • 好吧,让我们这样说吧。就速度而言,这并不重要,但要使用 find 控制函数的行为 - 您需要调整“find”命令行参数,而不是使用代码方式来控制函数行为。一方面,我不会选择 find,除非有非常具体的理由这样做。
  • 你说如果我只查找我可以使用的文件:-type f 而不是在 php 中 is_file 或 is_dir?
  • 是的,如果您只想查找文件,可以这样做。
猜你喜欢
  • 2015-06-14
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
相关资源
最近更新 更多