測試環境與方法
- 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)。
使用建議
| 場景 | 推薦函數 | 理由 |
| 建立新空檔 / 覆寫內容 | file_put_contents($path, '') | 速度快、語意清晰 |
| 僅更新時間戳(快取驗證、同步觸發) | touch($path) | 語意精確、不改變內容 |
| 大量建立臨時檔 | tempnam() 或 sys_get_temp_dir() | 自動處理唯一命名與清理 |
補充:原子性建立(避免競態)
<?php
// 獨佔建立:失敗若檔案已存在
$fp = fopen($path, 'x'); // 'x' 模式:建立並開啟唯寫,失敗回傳 false
if ($fp) {
fclose($fp);
}
// 或使用 flock 搭配
?>
- 上一篇文章: PHP 防注入淺析:addslashes 失效原理與正確防禦姿勢
- 下一篇文章: PHP 陣列儲存至檔案:var_export 與 include 的最佳實踐
Copyright ©
程式碼之家 All Rights Reserved