note 47362 deleted from function.readdir by tularis
| From: | tularis@php.net | Date: | Sun, 13 May 2007 19:04:51 +0000 |
| Subject: | note 47362 deleted from function.readdir by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-126535@lists.php.net to get a copy of this message | ||
Note Submitter: Jason Wong
----
Everyone seems to be using recursion for trawling through subdirectories. Here's a function
that does not use recursion.
<?php
function list_directory($dir) {
$file_list = '';
$stack[] = $dir;
while ($stack) {
$current_dir = array_pop($stack);
if ($dh = opendir($current_dir)) {
while (($file = readdir($dh)) !== false) {
if ($file !== '.' AND $file !== '..') {
$current_file = "{$current_dir}/{$file}";
if (is_file($current_file)) {
$file_list[] = "{$current_dir}/{$file}";
} elseif (is_dir($current_file)) {
$stack[] = $current_file;
}
}
}
}
}
return $file_list;
}
?>
I also did a rudimentary benchmark against Rick's function (no reason in particular why I chose
Rick's, it was just the latest) and the result is that using recursion results in about 50%
longer execution time.
Details of benchmark:
Directory contains 64 subdirectories and about 117,000 files. Each function was executed 100 times
in a for-loop and the average time per iteration was calculated. The result is 3.77 seconds for the
non-recursive function and 5.65 seconds for the recursive function.