2
\$\begingroup\$

I'm trying to optimize performance for recursive directory listing with some exceptions:

function listdir($basedir) {
    global $root, $ignore_dirs, $ignore_files, $filetypes, $ignore_starts_with;
        if ($handle = @opendir($basedir)) { 
            while (false !== ($fn = readdir($handle))) { 
                if ($fn != '.' && $fn != '..') {

                    $s = true;
                    foreach ($ignore_starts_with as $pre) if (strpos($fn, $pre) === 0) $s = false;

                    $dir = $basedir."/".$fn;
                    if ($s && is_dir($dir) && !in_array($fn, $ignore_dirs)) {
                        listdir($dir);
                    } else {

                        if ($s && !in_array($fn,$ignore_files) && preg_match("/[^.\/].+\.($filetypes)$/",$dir,$fname)) printlink($fname[0]);
                    } 
                } 
            } 
        closedir($handle); 
    } 
}
\$\endgroup\$
3
  • 3
    \$\begingroup\$ Optimize how? Where is the bottleneck? What have your profiling results shown? \$\endgroup\$
    – Ed S.
    Jul 29, 2011 at 17:51
  • \$\begingroup\$ im not shire about foreach construction, and many if's \$\endgroup\$
    – 350D
    Jul 29, 2011 at 18:27
  • 3
    \$\begingroup\$ Well, I would prove that is actually a bottleneck before potentially wasting time optimizing them out (if that's even possible). For example, if 98% of your time is spent doing I/O then removing an if statement or a loop is pointless. That said, your $s variable will only hold the last assignment, so you may as well just break out of it the first time that condition is met. \$\endgroup\$
    – Ed S.
    Jul 29, 2011 at 18:39

1 Answer 1

2
\$\begingroup\$

First of all, I'd use RecursiveDirectoryIterator, removed globals and corrected formatting.

Then used Xdebug + CacheGrind to try different versions.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.