本系列整理 PHP 核心效能優化技巧,分四部分說明。第一部分涵蓋檔案操作、資料庫、內建函數、迴圈與變數管理。
<?php
// ✅ 推薦:單次呼叫、內建最佳化、支援記憶體映射
$content = file_get_contents('test.txt');
// ❌ 避免:多函數呼叫、手動迴圈
$fp = fopen('test.txt', 'r');
while (!feof($fp)) { $content .= fgets($fp); }
fclose($fp);
注意:`file_get_contents()` 開啟 URL 需 `allow_url_fopen=On`,且 PHP 版本行為略有差異。
// ✅ 內建:C 實作、高度優化
sort($arr);
json_encode($data);
strtotime($date);
// ❌ 自寫:PHP 層面解釋執行、慢數倍
function my_sort($arr) { ... }
// ❌ 每次迴圈新建物件
for ($i=0; $i<10000; $i++) {
$obj = new HeavyClass();
$obj->process($data[$i]);
}
// ✅ 迴圈外建立,迴圈內重用
$obj = new HeavyClass();
for ($i=0; $i<10000; $i++) {
$obj->reset();
$obj->process($data[$i]);
}
// ❌ 多層迴圈賦值
foreach ($users as $u) {
foreach ($u['posts'] as $p) {
$result[] = [$u['name'], $p['title']];
}
}
// ✅ array_map/array_column 函數式處理
$result = array_merge(...array_map(function($u) {
return array_map(fn($p) => [$u['name'], $p['title']], $u['posts']);
}, $users));
// ✅ 簡單替換
str_replace(['{name}', '{date}'], [$name, $date], $template);
// ✅ 字元轉換
strtr($str, ['<' => '<', '>' => '>']);
// ❌ 過度使用正則
preg_replace('/\{name\}/', $name, $template);
// opcode 對比: // ++$i : 3 條指令 // $i++ : 4 條指令(產生臨時變數)
$bigData = load_huge_data(); process($bigData); unset($bigData); // 釋放記憶體,降低峰值
// ✅ O(1) 附加 $temp[] = $field; // ❌ 每次呼叫 count() $temp[count($temp)] = $field;
class Foo {
public static function bar() { echo 'static'; }
}
// ✅ 靜態呼叫:無需實例化、快 50-60%
Foo::bar();
// ❌ 實例呼叫靜態方法:產生 E_STRICT、轉換開銷
$foo = new Foo();
$foo->bar();