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

Viewed 38063

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.

However, profiling has shown that this is the slowest part of generating our pages with file_exists() taking up to 1/2 ms per file. We are only testing 40 or so files, but this still pushes 20ms onto the page load time.

Can anyone suggest a way of making this go faster? Is there a better way of testing if the file is present? If I build a cache of some kind, how should I keep it in sync.

20 Answers

In 2021, 12 years later since the question was asked I have the same use case. I check with file_exist for around 40 images in a loop before I decide what to show.

The figures (PHP 7.4) in milliseconds:

  • on local dev machine (Win10, WAMP, Samsung SSD): roughly 0.1 (1/10) millisecond per image, roughly 1000 images in the folder;
  • on server (pretty basic cheap one, VPS 1 Intel Xeon, RAM 2GB, SSD, Ubuntu, LAMP): roughly 0.01 (1/100) millisecond per image, 14,000 images in the folder;

The server is 10 times faster than the dev machine, and quite indistinguishable from overall UX performance POV where 30-50 ms is somewhat first noticeable threshold.

On server checking the array of 40 images I spend 0.4 ms to check if anyone of them not-existent. BTW no difference in performance whether some of the images exist or not.

So this should be of no question whether to check with file_exist or not because of disk performance. Check if you need.

Related