Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_file/file_exists performance and cache

I made some tests to compare and measure speed of both functions. is_file seems to be several times faster (I used 10000 iterations for both) than file_exists . I wonder if PHP or OS use some cache for these functions or does is always access HDD ? I think no, but I wonder...

I used this code:

<?php
$time = microtime();
$time = explode(' ', $time);
$begintime = $time[1] + $time[0];
for($i=0;$i<10000;$i++)
    file_exists('/Applications/MAMP/htdocs/index.php');
$time = microtime();
$time = explode(" ", $time);
$endtime = $time[1] + $time[0];
$totaltime = ($endtime - $begintime);
echo 'PHP parsed this in ' .$totaltime. ' seconds.</br>';
$time = microtime();
$time = explode(" ", $time);
$begintime = $time[1] + $time[0];
for($i=0;$i<10000;$i++)
    is_file('/Applications/MAMP/htdocs/index.php');
$time = microtime();
$time = explode(" ", $time);
$endtime = $time[1] + $time[0];
$totaltime = ($endtime - $begintime);
echo 'PHP parsed this in ' .$totaltime. ' seconds.</br>';
?>
like image 358
chubbyk Avatar asked Nov 04 '10 16:11

chubbyk


3 Answers

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

Affected functions include stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().

like image 106
Mark Baker Avatar answered Nov 01 '22 04:11

Mark Baker


PHP caches both is_file() and file_exists() in the stat cache. Call clearstatcache() to clear it.

Edit:
If anything, the two should take similar amounts of time because they both call the OS's stat() function, but the results of one may be cached for the other by PHP (unless you clearstatcache()) or by the OS as Yuliy mentions below.

like image 43
Powerlord Avatar answered Nov 01 '22 05:11

Powerlord


is_file and file_exists are two different function that does two different things; file_exists only check if the file exists, is_file tell if the target is a valid file, and (for example) not a directory.

They shouldnt be used for the same goal, so the performance comparison cant be done (imho)

like image 41
Strae Avatar answered Nov 01 '22 06:11

Strae