萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 大檔案高效讀寫:百萬行資料處理效能優化實戰

處理百萬行以上的大型文字檔(如日誌、匯出資料)時,讀寫效能至關重要。本文分享三個實測有效的優化方向:檔案讀取、陣列遍歷、資料儲存。

一、檔案讀取:避開 file(),改用 file_get_contents() + explode()

file() 會將整個檔案讀入陣列,記憶體佔用大且速度慢。對於「每行一筆資料」的規則檔案:

// 慢
$data = file($file);

// 快約 30% 以上
$data = explode("\n", file_get_contents($file));

原理:file_get_contents() 一次讀入字串,explode() 在 C 層級分割,比 file() 的逐行處理快得多。

二、陣列遍歷:翻轉陣列鍵值,用索引查找替代 in_array()

需判斷某值是否存在於大陣列中時,in_array() 是 O(n) 線性搜尋,極慢。解法:將陣列翻轉,值變鍵,值設為 1:

$lookup = array_flip($big_array); // 值變鍵
// 判斷存在
if (isset($lookup['target_value'])) { /* 存在 */ }

// 或直接初始化時就建立索引陣列
$indexed = [];
foreach ($big_array as $val) {
    $indexed[$val] = 1;
}
if ($indexed['target_value'] ?? false) { /* 存在 */ }

查找複雜度從 O(n) 降為 O(1),效能提升數百倍。

三、資料儲存:serialize() 勝過 var_export() 與 json_encode()

測試三種方式將大陣列寫入檔案:

方式寫入程式碼讀取程式碼相對效能
PHP 程式碼file_put_contents($f, '$var = require $f;最慢
serializefile_put_contents($f, serialize($var))$var = unserialize(file_get_contents($f));最快
JSONfile_put_contents($f, json_encode($var))$var = json_decode(file_get_contents($f), true);次快,接近 serialize

結論: PHP 原生序列化 serialize()/unserialize() 在大資料量下效能最佳,JSON 其次,寫成 PHP 檔案最慢(需經過編譯器解析)。

綜合建議

  1. 讀取:explode("\n", file_get_contents($file))
  2. 查找:建立索引陣列 $indexed[$val] = 1,用 isset() 判斷
  3. 儲存:file_put_contents($file, serialize($data))
  4. 若資料極大(超過記憶體),改用資料庫或分塊處理(fseek/fread)
copyright © 萬盛學電腦網 all rights reserved