PHP is_file與file_exists區別
阿新 • • 發佈:2018-12-20
通過以下程式碼可以測試出兩個函式的效率:
$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"; }