首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 建立空檔案:file_put_contents vs touch 效能實測

     編輯:PHP 綜合知識

測試環境與方法

  • PHP 7.x / Linux
  • 迴圈建立 100 個空檔案
  • 使用 microtime(true) 計時

程式碼

<?php
// 方法 1: file_put_contents
$start = microtime(true);
for ($i = 0; $i < 100; $i++) {
    file_put_contents("dir/file_$i", '');
}
echo "file_put_contents: " . (microtime(true) - $start) . " 秒\n";

// 方法 2: touch
$start = microtime(true);
for ($i = 0; $i < 100; $i++) {
    touch("dir/file_$i");
}
echo "touch: " . (microtime(true) - $start) . " 秒\n";
?>

測試結果(典型值)

函數平均耗時相對速度
file_put_contents()~0.11 秒基準 (1x)
touch()~0.23 秒約 2.1 倍較慢

深度解析

  • file_put_contents() 以 FILE_APPEND 模式開啟檔案,若不存在則建立,寫入空字串後關閉。內部優化較好。
  • touch() 需更新檔案存取/修改時間,涉及更多系統呼叫(utimensat 等)。
  • 若檔案已存在,touch() 僅更新時間戳;file_put_contents() 會截斷檔案(除非加 FILE_APPEND)。

使用建議

補充:原子性建立(避免競態)

<?php
// 獨佔建立:失敗若檔案已存在
$fp = fopen($path, 'x'); // 'x' 模式:建立並開啟唯寫,失敗回傳 false
if ($fp) {
    fclose($fp);
}
// 或使用 flock 搭配
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
場景推薦函數理由
建立新空檔 / 覆寫內容file_put_contents($path, '')速度快、語意清晰
僅更新時間戳(快取驗證、同步觸發)touch($path)語意精確、不改變內容
大量建立臨時檔tempnam() 或 sys_get_temp_dir()自動處理唯一命名與清理