is_file/file_exists性能和缓存

chu*_*byk 7 php performance

我做了一些测试来比较和测量两种功能的速度.is_file似乎比file_exists快几倍(我使用10000次迭代).我想知道PHP或OS是否为这些功能使用了一些缓存,或者是否始终访问HDD?我想不,但我想知道......

我用过这段代码:

<?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>';
?>
Run Code Online (Sandbox Code Playgroud)

Pow*_*ord 9

PHP缓存两者is_file()以及file_exists()stat缓存中的缓存.打电话clearstatcache()来清除它.

编辑:
如果有的话,这两个应该花费相似的时间,因为他们都调用操作系统的stat()功能,但一个的结果可以通过PHP(除非你clearstatcache())或由Yuliy提到的操作系统缓存.

  • 请注意,由于操作系统的文件系统缓存,文件操作的性能测量会有所不同 (2认同)

Mar*_*ker 9

当您使用stat(),lstat()或受影响的函数列表(下面)中列出的任何其他函数时,PHP会缓存这些函数返回的信息,以便提供更快的性能.但是,在某些情况下,您可能希望清除缓存的信息.例如,如果在单个脚本中多次检查同一文件,并且该文件在该脚本操作期间有被删除或更改的危险,则可以选择清除状态缓存.在这些情况下,您可以使用clearstatcache()函数清除PHP缓存文件的信息.

受影响的函数包括stat(),lstat(),file_exists(),is_writable(),is_readable(),is_executable(),is_file(),is_dir(),is_link(),filectime(),fileatime(),filemtime() ,fileinode(),filegroup(),fileowner(),filesize(),filetype()和fileperms().

  • 首先执行`file_exists()`测试,它必须从磁盘中实际读取并存储到statcache; 然后执行`is_file()`,它只读取已经由`file_exists()`检查填充的statcache条目,因此它(更不用说)更快了.在测试之间刷新缓存,然后你将准确地测试`is_file()`,因为它必须检查磁盘并以与`file_exists()`相同的方式填充缓存 (3认同)
  • 但是这两个函数都在那个列表中,所以这似乎并不能解释为什么一个函数会比另一个函数快得多. (2认同)