Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php recursive folder readdir vs find performance

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

like image 728
rcs20 Avatar asked Nov 30 '11 01:11

rcs20


2 Answers

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.

like image 75
aki Avatar answered Oct 01 '22 01:10

aki


'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.

like image 32
favoretti Avatar answered Oct 01 '22 01:10

favoretti