File_exists () versus in_array () scandir () - which is faster?

Say we have a loop like this:

foreach($entries as $entry){ // let say this loops 1000 times
   if (file_exists('/some/dir/'.$entry.'.jpg')){
      echo 'file exists';
   }
}

I assume that it should access the hard drive 1000 times and check if every file exists.

How about this one?

$files = scandir('/some/dir/');
foreach($entries as $entry){ // let say this loops 1000 times
   if (in_array($entry.'.jpg', $files)){
      echo 'file exists';
   }
}

Question 1: If it accesses the hard drive once, I believe that it should be much faster. Am I right on that?

However, if I need to check subdirectories for a file, for example:

foreach($entries as $entry){ // let say this loops 1000 times
   if (file_exists('/some/dir/'.$entry['id'].'/'.$entry['name'].'.jpg')){
      echo 'file exists';
   }
}

Question 2: If I want to apply the technique described above (files in an array) to check if there are entries, how can I scandir()subdirectories in an array so that I can compare the existence of a file using this method?

+5
source share
2 answers

, scandir() , , , file_exists(), , .

, glob(). , . .

, script, :

<?php

// Get the start time
$time_start = microtime(true);

// Do the glob() method here

// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;

echo '\'glob()\' finished in ' . $time . 'seconds';

// Do the file_exists() method here

// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;

echo '\'file_exists()\' finished in ' . $time . 'seconds';

// Do the scandir() method here

// Get the finish time
$time_end = microtime(true);
$time = $time_end - $time_start;

echo '\'scandir()\' finished in ' . $time . 'seconds';

?>

, script , , ,

1

memory_get_usage(), , PHP . . . .

2

, , . . :

php

+5

.

" ", , ,

<?php
   $start = microtime();
    //Your code
    $end = microtime();
    $result= $now-$then;
    echo $result;
?>

, scandir() , in_array().

0

All Articles