我一直在尝试复制 Gnu Find ("find .") 在 PHP 中,但似乎不可能接近它的速度。 PHP 实现使用的时间至少是 Find 的两倍。有没有用 PHP 更快的方法?
编辑:我添加了一个使用 SPL 实现的代码示例——它的性能等同于迭代方法
EDIT2:当从 PHP 调用 find 时,它实际上比本地 PHP 实现慢。我想我应该对我所拥有的感到满意:)
// measured to 317% of gnu find's speed when run directly from a shell
function list_recursive($dir) {
if ($dh = opendir($dir)) {
while (false !== ($entry = readdir($dh))) {
if ($entry == '.' || $entry == '..') continue;
$path = "$dir/$entry";
echo "$path\n";
if (is_dir($path)) list_recursive($path);
}
closedir($d);
}
}
// measured to 315% of gnu find's speed when run directly from a shell
function list_iterative($from) {
$dirs = array($from);
while (NULL !== ($dir = array_pop($dirs))) {
if ($dh = opendir($dir)) {
while (false !== ($entry = readdir($dh))) {
if ($entry == '.' || $entry == '..') continue;
$path = "$dir/$entry";
echo "$path\n";
if (is_dir($path)) $dirs[] = $path;
}
closedir($dh);
}
}
}
// measured to 315% of gnu find's speed when run directly from a shell
function list_recursivedirectoryiterator($path) {
$it = new RecursiveDirectoryIterator($path);
foreach ($it as $file) {
if ($file->isDot()) continue;
echo $file->getPathname();
}
}
// measured to 390% of gnu find's speed when run directly from a shell
function list_gnufind($dir) {
$dir = escapeshellcmd($dir);
$h = popen("/usr/bin/find $dir", "r");
while ('' != ($s = fread($h, 2048))) {
echo $s;
}
pclose($h);
}
最佳答案
我不确定性能是否更好,但您可以使用递归目录迭代器来简化代码...请参阅 RecursiveDirectoryIterator
和 'SplFileInfo` .
$it = new RecursiveDirectoryIterator($from);
foreach ($it as $file)
{
if ($file->isDot())
continue;
echo $file->getPathname();
}
关于php - 是否可以在 PHP 中加速递归文件扫描?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/624120/