Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 794
Rik Heywood Avatar asked Nov 10 '09 15:11

Rik Heywood


2 Answers

file_exists() should be a very inexpensive operation. Note too that file_exists builds its own cache to help with performance.

See: http://php.net/manual/en/function.file-exists.php

like image 184
RC. Avatar answered Oct 15 '22 18:10

RC.


Use absolute paths! Depending on your include_path setting PHP checks all(!) these dirs if you check relative file paths! You might unset include_path temporarily before checking the existence.

realpath() does the same but I don't know if it is faster.

But file access I/O is always slow. A hard disk access IS slower than calculating something in the processor, normally.

like image 23
powtac Avatar answered Oct 15 '22 17:10

powtac