php判斷檔案是否存在file_exists()函數使用詳解

來源:互聯網
上載者:User
導讀:在寫程式時發現在判斷檔案是否存在時,有兩種寫法,有的人用了is_file,有的人用了file_exists,用哪個更好或者說更合適呢?判斷檔案存在用is_file還是file_exists?在寫程式時發現在判斷檔案是否存在時,有兩種

但是, 這兩個函數的效能可不一樣, is_file() 比 file_exists() 會快點。

如果要檢查的檔案存在,那麼is_file() 比 file_exists() 快很多倍,但如果檔案不存在,則兩者差不多。

以下是測試的結果,第一個測試是檔案存在的,第二個是檔案不存在的:

第一次測試,檔案存在

<?php  // 運行 file_exists 10000 次  $time = microtime();  $time = explode(' ', $time);  $begintime = $time[1] + $time[0];  for($i=0;$i<10000;$i++)      file_exists('/Users/Jacky');         // 檔案存在  $time = microtime();  $time = explode(" ", $time);  $endtime = $time[1] + $time[0];  $totaltime = ($endtime - $begintime);  echo '運行file_exists 10000 次所花時間: ' .$totaltime. ' 秒'.PHP_EOL;      // 運行 is_file 10000 次  $time = microtime();  $time = explode(" ", $time);  $begintime = $time[1] + $time[0];  for($i=0;$i<10000;$i++)      is_file('/Users/Jacky');  $time = microtime();  $time = explode(" ", $time);  $endtime = $time[1] + $time[0];  $totaltime = ($endtime - $begintime);  echo '運行 is_file 10000 次所花時間: ' .$totaltime. ' 秒.'.PHP_EOL;

第二次測試,檔案不存在

<?php  // 運行 file_exists 10000 次  $time = microtime();  $time = explode(' ', $time);  $begintime = $time[1] + $time[0];  for($i=0;$i<10000;$i++)      file_exists('/Users/Jackys');         // 檔案不存在  $time = microtime();  $time = explode(" ", $time);  $endtime = $time[1] + $time[0];  $totaltime = ($endtime - $begintime);  echo '運行file_exists 10000 次所花時間: ' .$totaltime. ' 秒'.PHP_EOL;      // 運行 is_file 10000 次  $time = microtime();  $time = explode(" ", $time);  $begintime = $time[1] + $time[0];  for($i=0;$i<10000;$i++)      is_file('/Users/Jackys');  $time = microtime();  $time = explode(" ", $time);  $endtime = $time[1] + $time[0];  $totaltime = ($endtime - $begintime);  echo '運行 is_file 10000 次所花時間: ' .$totaltime. ' 秒.'.PHP_EOL;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.