【发布时间】:2011-05-05 04:30:33
【问题描述】:
我做了一些测试来比较和测量这两种功能的速度。 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>';
?>
【问题讨论】:
-
你是否在一个紧密的循环中多次调用这个(这个效果将支配请求时间)?如果不是,除非您确定它会导致性能问题,否则我不会担心它...请记住
Premature optimization is the root of all evil... 使用语义上更好的替代方案,直到您知道这是一个问题,然后才进行优化... -
确实,is_file() 比 file_exists() 快 10 倍!刚刚试了一下,确实是这样。
-
如果它对任何人都有帮助,我们可以添加 file_exists() 将为存在的目录和文件返回 true,其中 is_file() 只有在文件(当然存在)时才会返回 true .
标签: php performance