統計大型文字檔行數時,方法選擇直接影響記憶體與執行速度。本文比較兩種常見做法並給出建議。
<?php
$filePath = 'large_log.txt';
$lineCount = 0;
$fp = fopen($filePath, 'r');
if ($fp) {
// PHP 5.1+ 支援 stream_get_line,效能優於 fgets
while (stream_get_line($fp, 8192, "\n") !== false) {
$lineCount++;
}
fclose($fp);
}
echo "行數:$lineCount";
?>
memory_limit。file() 讀入陣列再計數(簡單但耗記憶體)<?php
$lineCount = count(file('large_log.txt'));
echo "行數:$lineCount";
Allowed memory size exhausted。| 方法 | 記憶體峰值 | 執行時間 |
|---|---|---|
| stream_get_line | ~2 MB | ~1.2 秒 |
| file() + count() | ~250 MB | ~0.8 秒 |
結論: 生產環境處理大檔案務必使用串流讀取;小檔案或一次性腳本可用 file() 簡化代碼。