rcs*_*s20 28 php system find readdir
我遇到了一些关于性能和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 $file\n";
getDirectory( "$path/$file", ($level+1) );
} else {
echo "$spaces $file\n";
}
}
}
closedir( $dh );
}
getDirectory( "." );
Run Code Online (Sandbox Code Playgroud)
这正确地回显文件/文件夹.
现在我发现了这个:
$t = system('find');
print_r($t);
Run Code Online (Sandbox Code Playgroud)
这也找到了所有的文件夹和文件然后我可以像第一个代码一样创建一个数组.
我认为system('find');
比这更快readdir
但我想知道它是否是一个好习惯?非常感谢你
aki*_*aki 36
这是我的基准测试,使用一个简单的for循环,在我的服务器上进行10次迭代:
$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
}
}
Run Code Online (Sandbox Code Playgroud)
显然,如果您的网站上有大量流量,readdir的使用速度会更快.