static (PHP 5+)<?php
class Foo {
public static function bar() { echo 'foobar'; }
}
// 靜態呼叫靜態方法:快 50-60% (避免 E_STRICT 警告與內部轉換)
Foo::bar();
// 實例呼叫靜態方法:較慢
$foo = new Foo(); $foo->bar();
<?php
class Config {
const DB_HOST = 'localhost';
const MAX_RETRY = 3;
}
// 優點:編譯期解析、雜湊表更小、命名空間隔離、除錯友善
echo Config::DB_HOST;
require_once/include_once每次呼叫都會開啟檔案檢查。PHP 5.2+/APC/OPcache 已優化。使用絕對路徑 +
require效能最佳。
<?php
// 慢:函數呼叫開銷
php_uname('s') == PHP_OS; // 3500% 慢
php_version() == PHP_VERSION; // 3500% 慢
php_sapi_name() == PHP_SAPI; // 3500% 慢
<?php $isWin = DIRECTORY_SEPARATOR === '\\'; // 無函數呼叫、跨版本通用
<?php // 慢:time() 函數呼叫 // 快:$_SERVER['REQUEST_TIME'] (無函數呼叫,請求開始時間戳)
<?php
// 不需捕獲組時使用非捕獲組 (?:...)
preg_match('/(?:pattern)/', $str); // 省去記憶體分配,快 ~15%
// 能用字串函數別用正則
strpos(), strrpos(), stripos(), strripos(), strncasecmp()
strtr 字元級替換優化<?php // 快 10 倍:字串對字串 $addr = strtr($addr, "abcd", "efgh"); // 慢:陣列對應 $addr = strtr($addr, ['a'=>'e', 'b'=>'f', 'c'=>'g', 'd'=>'h']);
str_replace<?php
// 慢:即使不替換也分配記憶體
str_replace($search, $replace, $subject);
// 快:先檢查是否存在
if (strpos($subject, $search) !== false) {
str_replace($search, $replace, $subject);
}
// 不需替換時快 200%
@ 抑制錯誤
@內部操作複雜,慢 3 倍。迴圈中絕對禁用。替代:error_reporting(0)區塊包裹。
strncmp 前綴比較<?php // 比較前 N 字元 strncmp($str1, $str2, $n); // 比 substr/strtolower/PCRE 快
substr_compare (PHP 5+)除非「忽略大小寫 + 較大字串」,否則比
substr+ 比較更慢。
需雙重雜湊查找、轉小寫、產生 E_NOTICE、建立臨時字串。慢 700%。
<?php
// 慢:每次迴圈呼叫 count()
for ($i = 0; $i < count($arr); $i++) {}
// 快:預計算
for ($i = 0, $max = count($arr); $i < $max; ++$i) {}
<?php
// 目錄遍歷效能對比
// 原生 OO: 3.37s
// glob(): 6.28s
// scandir(): 3.42s
// 非 OO: 3.14s (最快)
$d = dir('.'); while (($e = $d->read()) !== false) { ... }
<?php include 'file.php'; // 差:相對路徑需解析 include './file.php'; // 好:明確相對路徑 include '/path/to/file.php'; // 最佳:絕對路徑
<?php // 手寫讀取檔案 $h = fopen($f, 'rb'); $c = fread($h, filesize($f)); fclose($h); // 內建一行搞定 $c = file_get_contents($f);
<?php
// 簡化深層陣列存取
$ref =& $a['b']['c'];
for ($i = 0; $i < 5; ++$i) $ref[$i] = $i;
// 大字串傳遞避免複製
function appendRef(&$str) { $str .= 'suffix'; } // 記憶體友善
function appendVal($str) { return $str . 'suffix'; } // 複製字串
| 策略 | 效果 | 實施建議 |
|---|---|---|
| OPcache 啟用 | 編譯緩存,提升 2-10 倍 | 生產環境必開,調整 opcache.memory_consumption |
| Composer 自動載入優化 | 減少檔案系統查找 | composer dump-autoload -o --classmap-authoritative |
| 資料庫連線池 | 減少連線建立開銷 | ProxySQL、Swoole、PDO::ATTR_PERSISTENT |
| 快取策略 | 避免重複運算 | Redis 多層快取、HTTP 快取標頭、片段快取 |
| 非同步處理 | 釋放 Web 執行緒 | Swoole、Workerman、Queue Workers (RabbitMQ/Redis) |
| 靜態化/SSG | 極致回應速度 | 定期生成靜態頁、Varnish/Nginx fastcgi_cache |
| Profiling 導向優化 | 精準定位瓶頸 | Xdebug Profiler、Blackfire、Tideways |
PHP 優化是系統工程,語法微優化僅是冰山一角。真正的效能飛躍來自:架構選型正確、快取策略得當、資料庫設計合理、非同步解耦、靜態化極致。建議優先順序:架構 > 快取 > 資料庫 > 非同步 > 微優化。