i came across few articles about performance and readdir here is the php script:
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( "." );
this echo the files/ folders correctly.
now i found this:
$t = system('find');
print_r($t);
which also find all the folders and files then i can create an array like the first code.
i think the system('find');
is faster than the readdir
but i want to know if it'S a good practice?
thank you very much
Here's my benchmark using a simple for loop with 10 iteration on my server:
$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
}
}
Clearly the readdir is faster to use specially if you have lots of traffic on your site.
'find' is not portable, it's a unix/linux command. readdir() is portable and will work on Windows or any other OS. Moreover, 'find' without any parameters is recursive, so if you're in a dir with lots of subdirs and files, you will get to see all of them, rather than only the contents of that $path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With