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

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


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


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.


The fastest way to check existence of a local file is stream_resolve_include_path():

if (false !== stream_resolve_include_path($s3url)) {   //do stuff }

Performance results stream_resolve_include_path() vs file_exists():

Test name       Repeats         Result          Performance     stream_resolve  10000           0.051710 sec    +0.00%file_exists     10000           0.067452 sec    -30.44%

In test used absolute paths.Test source is here.PHP version:

PHP 5.4.23-1~dotdeb.1 (cli) (built: Dec 13 2013 21:53:21)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies