Skip to content

Instantly share code, notes, and snippets.

@franckweb
Last active September 1, 2025 11:00
Show Gist options
  • Select an option

  • Save franckweb/9f08a1fd9d37cd69d96a2f7bbb9d4ef4 to your computer and use it in GitHub Desktop.

Select an option

Save franckweb/9f08a1fd9d37cd69d96a2f7bbb9d4ef4 to your computer and use it in GitHub Desktop.
Read files from local directory with PHP, performance comparison between glob, scandir, readdir and DirectoryIterator.
<?php
/*
* Prints out time the specified method takes to run.
* Just need to add a bunch of files in your specified directory
*
* From console: php index.php [name_of_method] (ex: php index.php runiterator)
* From web request: go to http://yourdomain.test/?test=[name_of_method] (ex: http://yourdomain.test/?test=runglob)
*
*/
class ImageLoader
{
private $directory = 'yourdirectory/';
private function runiterator()
{
$results = array();
foreach (new DirectoryIterator($this->directory) as $fileInfo) {
$results[] = $fileInfo;
}
return $results;
}
private function runreaddir()
{
$results = array();
if ($handle = opendir($this->directory)) {
while (false !== ($filename = readdir($handle))) {
$results[] = $filename;
}
}
return $results;
}
private function runscandir()
{
$results = scandir($this->directory);
return $results;
}
private function runglob()
{
$results = glob($this->directory . '/*', GLOB_NOSORT);
return $results;
}
public function run($method = '')
{
if (is_string($method)){
return $this->{$method}();
}
}
}
$start = microtime(true);
$loader = new ImageLoader;
// check if running from console or as web request
if (defined('STDIN') && isset($argv[1])) {
$loader->run($argv[1]);
} elseif(isset($_GET['test'])) {
$loader->run($_GET['test']);
}
$end = microtime(true);
echo ($end-$start)*1000;
echo "\n";
@dannyvankooten
Copy link

dannyvankooten commented Sep 1, 2025

For anyone wondering about a ballpark estimate of results without needing to run this yourself.

100 iterations on a directory containing 1000 files:

iterator:   	68.853 ms		0.689 / it
readdir:   		38.000 ms		0.380 / it
scandir:   		48.612 ms		0.486 / it
glob:   		56.697 ms		0.567 / it

Without sorting (GLOB_NOSORT, SCANDIR_SORT_NONE):

iterator:   	69.164 ms		0.692 / it
readdir:   		38.146 ms		0.381 / it
scandir:   		35.990 ms		0.360 / it
glob:   		45.717 ms		0.457 / it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment