PHP 解釋執行的性能瓶頸在於「編譯 → 執行」的重複開銷。Opcode 緩存將編譯後的字節碼存入共享內存,直接跳過編譯階段。本文對比三大主流方案:
; php.ini / php.d/opcache.ini zend_extension=opcache.so opcache.enable=1 opcache.enable_cli=1 opcache.memory_consumption=256 ; MB,根據代碼體量調整 opcache.interned_strings_buffer=16 opcache.max_accelerated_files=20000 ; 超過項目文件數 opcache.revalidate_freq=60 ; 生產 60s,開發 0 opcache.fast_shutdown=1 opcache.validate_timestamps=1 opcache.save_comments=1 ; 註解保留(註解驅動框架需求) opcache.jit=1255 ; PHP 8.0+ JIT 開啟(tracing 模式) opcache.jit_buffer_size=128M
; 需編譯安裝,PHP 7+ 不再支持 [xcache-common] extension=xcache.so [xcache.admin] xcache.admin.enable_auth=On xcache.admin.user="admin" xcache.admin.pass="md5_hash" [xcache] xcache.size=64M xcache.count=1 xcache.slots=8K xcache.ttl=0 xcache.gc_interval=0 xcache.var_size=4M xcache.var_count=1 xcache.var_slots=8K xcache.var_ttl=0 xcache.var_maxttl=0 xcache.readonly_protection=Off xcache.mmap_path="/dev/zero" xcache.coredump_directory="" xcache.cacher=On xcache.stat=On xcache.optimizer=On xcache.coverager=Off xcache.coveragedump_directory=""
# Ubuntu 20.04+ apt install hhvm # 配置 /etc/hhvm/server.ini hhvm.server.port = 9000 hhvm.server.type = fastcgi hhvm.jit = true hhvm.jit_a_size = 134217728 hhvm.jit_a_cold_size = 134217728 hhvm.jit_global_data_size = 134217728 # Nginx 轉發至 127.0.0.1:9000
# 測試機:2 vCPU, 4GB RAM, Ubuntu 22.04, PHP 8.2 / HHVM 4.168 # 目標頁面:包含 DB 查詢、模板渲染、JSON 序列化的典型 API # 工具:wrk(現代 HTTP 基準工具,支援 Lua 腳本) # 預熱 wrk -t2 -c50 -d30s https://127.0.0.1:8080/api/test # 正式測試:持續 60 秒,100 併發 wrk -t4 -c100 -d60s --latency https://127.0.0.1:8080/api/test
| 指標 | 無加速器 | Opcache | Opcache+JIT | HHVM |
|---|---|---|---|---|
| QPS (req/s) | 1,200 | 3,800 | 4,500 | 5,200 |
| Avg Latency (ms) | 83 | 26 | 22 | 19 |
| P99 Latency (ms) | 210 | 45 | 38 | 35 |
| CPU 佔用 | 95% | 60% | 55% | 70% |
| 內存佔用 | 180MB | 320MB | 400MB | 800MB |
| 兼容性 | 100% | 100% | 99% | 90% |
hhvm-mysql)、不支援所有 PHP 擴展(如 pdo_oci、ssh2)。create_function、eval 行為差異)。# PHP 8.2 + Opcache + JIT(最佳平衡) opcache.enable=1 opcache.memory_consumption=512 opcache.interned_strings_buffer=32 opcache.max_accelerated_files=50000 opcache.revalidate_freq=60 opcache.validate_timestamps=1 opcache.fast_shutdown=1 opcache.jit=1255 opcache.jit_buffer_size=256M # PHP-FPM 池 pm = dynamic pm.max_children = 200 pm.start_servers = 30 pm.min_spare_servers = 20 pm.max_spare_servers = 50 pm.max_requests = 1000 request_terminate_timeout = 60s
opcache_get_status() 監控 memory_usage.used_memory / memory_usage.free_memory、opcache_statistics.hits / misses。hits / (hits + misses) > 99% 為健康;低於 95% 檢查 revalidate_freq 或文件變更頻率。opcache_get_status()['jit'] 查看 buffer_used、traces。request_slowlog_timeout = 5s + slowlog 定位熱點。xcache.ini,刪除編譯產物。opcache.so,按上述模板配置。xcache_get、xcache_set、xcache_inc),替換為 apcu 或 Redis。Opcache + JIT 是當前 PHP 生產環境的最優解:零外部依賴、官方長期維護、性能逼近 HHVM、兼容性 100%。HHVM 適合極端性能場景且團隊具備深度運維能力。Xcache 已成為歷史,存量專案應盡快遷移。核心原則:開啟 Opcode 緩存、配置足夠內存、啟用 JIT、監控命中率、定期壓測驗證。