找到包含特定项目的目录的最快方法

时间:2012-01-13 15:32:05

标签: php performance

我在Windows XP SP3上运行了一个PHP 5.3.4应用程序,我需要索引远程PC上目录的内容。我正在索引的最大目录包含大约18,000个项目。

此调用会找到\\somepc.mycorp.com\foo\mydir\bar\zoo.zip等项目。

// look in all the directories in \\somepc.mycorp.com\foo for directories containing a file \bar\zoo.zip
$item_list = GetFileList('\\\\somepc.mycorp.com\\foo', '\\bar\\zoo.zip');

它实现为:

function GetFileList($base_dir, $path_mask)
{
    $result= array();
    if ($handle = opendir($base_dir)) 
    {
        while (false !== ($entry = readdir($handle))) 
        {
            // only add items that match the mask we're looking for
            if ($entry != "." &&
                $entry != ".." && 
                file_exists($base_dir.'\\$entry\\$path_mask'))
            {
                array_push($result, $entry);
            }
        }

        closedir($handle);
    }
    return $result;
}

不幸的是,对于最大的目录结构,此操作可能需要一个多小时。如果我删除过滤器并将每个看到的项目插入阵列,它将在几秒钟内完成。

有没有更快的方法来实现这一目标?

1 个答案:

答案 0 :(得分:3)

我讨厌拉这张卡,但是使用bash甚至是windows脚本可以更快地完成你正在做的事情 - PHP可能不适合这里的工作。系统调用(甚至从PHP内部)到dir /s /bfind将获得存在的所有文件的列表,然后您可以比使用PHP迭代这些字符串要快得多,以查看是否每个目录中都有一个文件。

我会像这样在bash中这样做(因为我很懒,并且不知道正确的查找语法):

find | grep '/bar/zoo.zip'

我不知道相应的windows shell命令(因为我的机器上安装了WinGnu32 grep),所以我无法帮助你。

编辑:

我做了一些捏造,发现Windows等同于上面的命令:

dir /s /b | find "/bar/zoo.zip"