22
22

More than 5 years have passed since last update.

ファイル検索する際はopendirが早い

Last updated at Posted at 2013-08-25

globなんか遅いなあ、と思って他のファイル検索方法を調べてみました。

  • glob
  • opendir/readdir
  • DirectoryIndex

の3通りについて、実際に計測をしてみます。

test.php

<?php
function list_dir_by_opendir($dir)
{
    $ret[] = $dir;

    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            $file = $dir . DIRECTORY_SEPARATOR . $file;
            $ret[] = $file;
        }
        closedir($dh);
    }

    return $ret;
}

function list_dir_by_glob($dir)
{
    $ret[] = $dir;

    foreach( glob($dir.DIRECTORY_SEPARATOR.'{.*,*}',GLOB_BRACE) as $file ) {
        $ret[] = $file;
    }

    return $ret;
}

function list_dir_by_iterator($dir)
{
    $ret[] = $dir;

    foreach( new DirectoryIterator($dir) as $fileinfo ) {
        $ret[] = $fileinfo->getPathname();
    }

    return $ret;
}

$target_path = dirname(__FILE__);

$start1 = microtime(true);
for($i=0;$i<10000;$i++){
    $files1 = list_dir_by_opendir($target_path);
}
$elapse1 = round((microtime(true) - $start1) * 1000 / 10000,5);

$start2 = microtime(true);
for($i=0;$i<10000;$i++){
    $files2 = list_dir_by_glob($target_path);
}
$elapse2 = round((microtime(true) - $start2) * 1000 / 10000,5);

$start3 = microtime(true);
for($i=0;$i<10000;$i++){
    $files3 = list_dir_by_iterator($target_path);
}
$elapse3 = round((microtime(true) - $start3) * 1000 / 10000,5);

結果は、AMD1.5GHz/8GB/Win7の環境で

time1: 0.28807 msec
time2: 4.07651 msec
time3: 0.36839 msec

となり、opendir/readdirの圧勝となりました。
(DirectoryIteratorの計測方法が間違っていましたので訂正しました。こちらもかなり早いっぽいです)

以下、おまけとしてopendir/readdirを使ったファイル検索イテレータを作ってみました。
(2013.08.27 DirectoryIteratorの方が実測上高速でしたのでソースを削除しました。見てみたい方はご連絡ください)

22
22
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
22