Last active
July 26, 2024 21:00
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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