is_file和file_exists效率比較


目前在弄文件緩存的時候用到了判定文件存在與否,is_file()還是file_exists()呢?is_file和file_exists兩者效率比較起來,誰的運行速度更快呢?還是做個測試吧:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
$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

超過1分鍾了,別忘了在php第一行加句:
set_time_limit(120);//時間限制120秒

結論:

is_file()和file_exists()效率比較,結果當文件存在時,is_file函數比file_exists函數速度快14倍,當文件不存在時,兩者速度相當。同理,當文件目錄存在時,is_dir()比file_exists()快18倍。不存在時兩者效率相當。PHP的file_exists = is_dir + is_file。
* 如果要判斷目錄是否存在,請優先考慮函數 is_dir(directory)
* 如果要判斷文件是否存在,請優先考慮函數 is_file(filepath)

is_dir()對比file_exists()測試結果:

當目錄存在時,運行1萬次
is_dir–>0.0058560371398926
file_exits–>0.11063098907471
當目錄不存在時,運行1萬次
is_dir–>0.7159481048584
file_exits–>0.71305584907532


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM