PHP is_file与file_exists区别

版权声明:原创文章,转载请注明原文地址。 https://blog.csdn.net/it_r00t/article/details/84138867

通过以下代码可以测试出两个函数的效率:

$start_time = get_microtime();
for($i=0;$i<10000;$i++)//默认1万次,可手动修改
{
if(is_file('test.txt')) {
//do nothing;
}
}
echo 'is_file-->'.(get_microtime() - $start_time).'<br>';
$start_time = get_microtime();
for($i=0;$i<10000;$i++)//默认1万次,可手动修改
{
if(file_exists('test.txt')) {
 //do nothing;
}
}
echo 'file_exits-->'.(get_microtime() - $start_time).'<br>';
function get_microtime()//时间
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}



当文件存在时:
运行1万次:
is_file–>0.0067121982574463
file_exits–>0.11532402038574

运行10万次:
is_file–>0.069056034088135
file_exits–>1.1521670818329

当运行100万次:
is_file–>0.6924250125885
file_exits–>11.497637987137

当文件不存在时:

运行1万次:
is_file–>0.72184419631958
file_exits–>0.71474003791809

运行10万次:
is_file–>7.1535291671753
file_exits–>7.0911409854889

当运行100万次:
is_file–>72.042867183685
file_exits–>71.789203166962

  根据输出可以看出is_file的效率比file_exists要高出很多。在官方手册中关于is_file注释中有这么一句话:Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。发现is_file的结果会被缓存下来,造成了is_file效率较高。

<?php
/*
 * 区分is_file和file_exists区别
 * is_file有缓存,file_exists没有缓存
 */
$file = dirname(__FILE__).'/a.txt';
if(is_file($file)){
	echo "$file exists\n";
}else{
	echo "$file no exists\n";
}
echo "请删除文件$file\n";
sleep(10); // 这个时间段删除文件
if(is_file($file)){
	echo "$file exists\n";
}else{
	echo "$file no exists\n";
}
$fileb = dirname(__FILE__).'/b.txt';
if(file_exists($fileb)){
	echo "$file exists\n";
}else{
	echo "$file no exists\n";
}
echo "请删除文件$fileb\n";
sleep(10); // 这个时间段删除文件
if(file_exists($fileb)){
	echo "$file exists\n";
}else{
	echo "$file no exists\n";
}

猜你喜欢

转载自blog.csdn.net/it_r00t/article/details/84138867