6

次のようなループがあるとします。

foreach($entries as $entry){ // let's say this loops 1000 times
   if (file_exists('/some/dir/'.$entry.'.jpg')){
      echo 'file exists';
   }
}

これは、HDDに1000回アクセスして、各ファイルが存在するかどうかを確認する必要があると想定しています。

代わりにこれを行うのはどうですか?

$files = scandir('/some/dir/');
foreach($entries as $entry){ // let's say this loops 1000 times
   if (in_array($entry.'.jpg', $files)){
      echo 'file exists';
   }
}

質問 1:これが HDD に 1 回アクセスする場合、はるかに高速になるはずです。私はこれで正しいですか?

ただし、次のように、ファイルのサブディレクトリを確認する必要がある場合はどうなりますか。

foreach($entries as $entry){ // let's say this loops 1000 times
   if (file_exists('/some/dir/'.$entry['id'].'/'.$entry['name'].'.jpg')){
      echo 'file exists';
   }
}

質問 2:上記の手法 (配列内のファイル) を適用してエントリが存在するかどうかを確認する場合、scandir()この方法を使用してファイルの存在を比較できるように、配列にサブディレクトリを追加するにはどうすればよいですか?

4

2 に答える 2

5

私の意見ではscandir()、ディレクトリを一度だけ読み取るだけでなく、file_exists()非常に遅いことが知られているため、の方が高速になると思います。

さらに、 を使用できますglob()。これにより、特定のパターンに一致するディレクトリ内のすべてのファイルが一覧表示されます。こちらをご覧ください

私の意見に関係なく、次のような簡単なスクリプトを実行して速度をテストできます。

<?php

// Get the start time
$time_start = microtime(true);

// Do the glob() method here

// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;

echo '\'glob()\' finished in ' . $time . 'seconds';

// Do the file_exists() method here

// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;

echo '\'file_exists()\' finished in ' . $time . 'seconds';

// Do the scandir() method here

// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;

echo '\'scandir()\' finished in ' . $time . 'seconds';

?>

上記のスクリプトがキャッシュでどのように動作するかわかりません。テストを別々のファイルに分けて個別に実行する必要があるかもしれません

更新 1

memory_get_usage()PHP スクリプトに現在割り当てられているメモリの量を返す関数を実装することもできます。これは便利かもしれません。詳しくはこちらをご覧ください。

更新 2

2 番目の質問については、サブディレクトリを含むディレクトリ内のすべてのファイルを一覧表示する方法がいくつかあります。この質問への回答を参照してください。

ディレクトリとサブディレクトリ内のファイルをスキャンし、php を使用してそれらのパスを配列に保存します

于 2013-01-25T08:09:08.743 に答える
0

ここで見ることができます。

などの「質問コード」を修正しました。

<?php
   $start = microtime();
    //Your code
    $end = microtime();
    $result= $now-$then;
    echo $result;
?>

scandir()個人的には より速いと思いますin_array()

于 2013-01-25T08:09:19.527 に答える