目前在弄文件緩存的時候用到了判定文件存在與否,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
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
