Skip to content

Instantly share code, notes, and snippets.

@franckweb
Last active April 14, 2021 16:54
Show Gist options
  • Save franckweb/9f08a1fd9d37cd69d96a2f7bbb9d4ef4 to your computer and use it in GitHub Desktop.
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";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment