用 PHP 的 file_put_contents 函數以追加的方式,迴圈 10 w 次寫檔案,耗時很多。因為 file_put_contents 函數每次都要開啟檔案,寫入檔案,然後關閉檔案。
以下是測試:
public function handle()
{
$testTxt = storage_path('test.txt');
for ($i = 0; $i < 100000; $i++) {
$this->comment('writing...');
file_put_contents($testTxt, 'wo shi tanteng.' . PHP_EOL, FILE_APPEND);
}
$this->comment('time:' . round(microtime(true) - LARAVEL_START, 2));
}
如圖所示:
耗時 165.76 秒。現在換一種寫檔案的方式,使用 fwrite 並且加鎖的方式同樣迴圈 10w 次寫入,代碼如下:
public function handle()
{
$testTxt = storage_path('test2.txt');
$handle = fopen($testTxt, 'wr');
flock($handle, LOCK_EX | LOCK_NB);
for ($i = 0; $i < 100000; $i++) {
$this->comment('writing...');
fwrite($handle, 'wo shi tanteng.' . PHP_EOL);
}
flock($handle, LOCK_UN);
fclose($handle);
$this->comment('time:' . round(microtime(true) - LARAVEL_START, 2));
}
運行效果如圖:
如圖所示,耗時 40.46 s,大大提高了效率。
跟 file_put_contents 函數比, fwrite 提高了寫檔案的效率,同時使用 flock 進行寫檔案加鎖,防止並發同時操作一個檔案。