我偶然看到一些关于性能和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 $filen";
getDirectory( "$path/$file", ($level+1) );
} else {
echo "$spaces $filen";
}
}
}
closedir( $dh );
}
getDirectory( "." );
这将正确地回显文件/文件夹。
现在我发现了这个:
$t = system('find');
print_r($t);
,它也可以找到所有的文件夹和文件,然后我可以创建一个数组,像第一个代码。
我认为system('find');
比readdir
快,但我想知道这是否是一个好的做法?非常感谢
下面是我在服务器上使用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使用起来更快,特别是当你的网站流量很大的时候
'find'是不可移植的,它是unix/linux命令。readdir()是可移植的,可以在Windows或任何其他操作系统上工作。此外,不带任何参数的'find'是递归的,因此,如果您在一个包含许多子目录和文件的目录中,您将看到所有子目录和文件,而不仅仅是该$path的内容。