How can the performance of a PHP function that recursively reads directories be optimized to reduce runtime significantly?

To optimize the performance of a PHP function that recursively reads directories, we can reduce the number of filesystem calls by storing the directory contents in memory and only accessing the disk when necessary. This can significantly reduce runtime by minimizing the overhead of repeated filesystem operations.

function readDirectory($dir) {
    $files = [];
    
    $handle = opendir($dir);
    
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            
            if (is_dir($path)) {
                $files = array_merge($files, readDirectory($path));
            } else {
                $files[] = $path;
            }
        }
    }
    
    closedir($handle);
    
    return $files;
}

// Usage
$directory = "/path/to/directory";
$files = readDirectory($directory);