简体   繁体   中英

improving speed of file existence checking

I use this code to check for file existence. It must use a wildcard:

$cachedFileResultArray = glob( '/directory/' . "$slugUrl*" ) ?? null;

From my understanding it will not stop upon first hit. Is there a way to improve this process, such as stop looking after first hit ? Or any other way to accomplish this the fastest way possible ?

I think you could use DirectoryIterator to speed up search. Try this function and benchmark perfomance.

function globIterator($dir, $pattern) {
    $directory = new RecursiveDirectoryIterator($dir);
    $iterator = new RecursiveIteratorIterator($directory);
    foreach($iterator as $file) {
        if (preg_match($pattern, $file) === 1){
            return $file;
        }
    }
    return null;
}

If wildcard is not a regex, it would be good to replace preg_match to strpos , as PHP documentation recommends , so foreach loop will lock like this:

foreach ($iterator as $file) {
    if (strpos($file, $pattern) !== false) {
        return $file;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM