file_exists() is too slow in PHP. Can anyone suggest a faster alternative?

后端 未结 19 1078
迷失自我
迷失自我 2021-02-05 01:18

When displaying images on our website, we check if the file exists with a call to file_exists(). We fall back to a dummy image if the file was missing.

Howe

19条回答
  •  孤独总比滥情好
    2021-02-05 01:52

    I'm not even sure if this will be any faster but it appears as though you would still like to benchmark soooo:

    Build a cache of a large array of all image paths.

    $array = array('/path/to/file.jpg' => true, '/path/to/file2.gif' => true);
    

    Update the cache hourly or daily depending on your requirements. You would do this utilizing cron to run a PHP script which will recursively go through the files directory to generate the array of paths.

    When you wish to check if a file exists, load your cached array and do a simply isset() check for a fast array index lookup:

    if (isset($myCachedArray[$imgpath])) {
        // handle display
    }
    

    There will still be overhead from loading the cache but it will hopefully be small enough to stay in memory. If you have multiple images you are checking for on a page you will probably notice more significant gains as you can load the cache on page load.

提交回复
热议问题