28

私はパフォーマンスと 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、それが良い方法かどうか知りたいですか? どうもありがとうございます

4

2 に答える 2

36

これは、サーバーで 10 回の反復を行う単純な for ループを使用した私のベンチマークです。

$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 を使用する方が高速です。

于 2011-11-30T13:55:56.613 に答える
2

「find」は移植性がなく、unix/linux コマンドです。readdir() は移植性があり、Windows またはその他の OS で動作します。さらに、パラメータなしの「検索」は再帰的であるため、多くのサブディレクトリとファイルがあるディレクトリにいる場合、その $path の内容だけではなく、それらすべてを見ることができます。

于 2011-11-30T01:40:24.473 に答える