Search code examples
phpperformancefile-exists

Optimize image output performance


I have a php file which checks if an image is available. If it is, the image will be returned to the user, if not it will be created and then returned to the user.

if(file_exists($filepath)) {
    $fp = fopen($filepath, 'rb'); # stream the image directly from the cachefile
    fpassthru($fp);
    exit;
} 

I guess to optimize this I can skip the "file_exists" call and just try to "fopen" it, if "false" is returned I create the image, otherwise I directly return it (is that correct?).

What I want to know is, is this the fastest way to load an image in PHP? Before that I used imagepng($image) but read that fpassthru is way faster: http://www.php.net/manual/en/function.imagepng.php#103787


Solution

  • The fastest way is not to process the image via PHP in the first place. Use reverse proxy server, which serve existing files, and for each not existing file it call's the PHP script.

    Next, removing call to file_exists() is microoptimization; however if the file do not exists PHP will trigger warning, write it to the log, output it depending on settings... which in terms of CPU is more expensive than the file_exists call.