萬盛學電腦網

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

PHP 迴圈中呼叫函數效能分析與優化

原始範例代碼

<?php
function calculate($period) {
    return cos(time() % $period);
}

$start = time();
$value = 0;

for ($i = 0; $i < 2000; $i++) {
    $value += calculate(360);
}

$finish = time();
echo "執行時間: " . ($finish - $start) . " 秒\n";
echo "value = $value\n";
?>

效能問題分析

  1. 重複呼叫 time():每次迴圈呼叫 calculate() 內部又呼叫 time(),系統呼叫開銷可避免。
  2. 函數呼叫開銷:PHP 函數呼叫有堆疊幀建構/銷毀成本,2000 次雖微小但在熱路徑可優化。
  3. 測量方式不精確:time() 秒級精度,短時間執行易為 0 秒;應用 microtime(true) 或 hrtime()。

優化版本

<?php
// 1. 將 time() 提至迴圈外
$now = time();
$period = 360;
$value = 0;

$start = microtime(true);
for ($i = 0; $i < 2000; $i++) {
    $value += cos($now % $period);
}
$elapsed = microtime(true) - $start;

echo "優化後執行時間: " . number_format($elapsed * 1000, 3) . " ms\n";
echo "value = $value\n";
?>

進階優化策略

1. 內聯函數 (Inline)

將函數邏輯直接寫在迴圈內,消除呼叫開銷:

for ($i = 0; $i < 2000; $i++) {
    $value += cos($now % 360);
}

2. 使用靜態變數快取

若函數內有昂貴初始化,用 static 避免重複:

function heavyCalc($x) {
    static $cache = [];
    if (!isset($cache[$x])) {
        $cache[$x] = expensive_operation($x);
    }
    return $cache[$x];
}

3. 預計算/查表法

若輸入域有限 (如 $period 固定),預先建立對應表:

$cosTable = [];
for ($i = 0; $i < 360; $i++) {
    $cosTable[$i] = cos($i);
}
for ($i = 0; $i < 2000; $i++) {
    $value += $cosTable[$now % 360];
}

4. 向量化運算 (PHP 8.1+ FFI / 拓展)

大量數學運算可考慮 FFI 呼叫 C 庫、或安裝 php-math、NumPHP 等擴展。

效能測試基準 (Benchmark)

<?php
function bench($name, callable $fn, $iterations = 10000) {
    $start = hrtime(true);
    for ($i = 0; $i < $iterations; $i++) $fn();
    $ns = hrtime(true) - $start;
    echo "$name: " . number_format($ns / $iterations / 1e6, 3) . " ms/iter\n";
}

$now = time();
bench('原版函數呼叫', fn() => cos($now % 360));
bench('內聯運算', fn() => cos($now % 360)); // 實際相同,示意
bench('查表法', function() use ($now) {
    static $t = null;
    $t ??= array_map('cos', range(0, 359));
    return $t[$now % 360];
});
?>

結論

  • 微優化 (內聯、提取常量) 在現代 PHP (7.4+/8.x) 差異極小,可讀性優先。
  • 真正瓶頸通常在 I/O (資料庫、API、檔案),應優先優化查詢、快取、非同步處理。
  • 使用 microtime(true) 或 hrtime() 進行精確測量,避免 time() 秒級誤差。
  • 開啟 OPcache (生產環境必開),JIT (PHP 8.0+) 可進一步優化熱路徑。
copyright © 萬盛學電腦網 all rights reserved