PHP性能优化实战:4个立竿见影的技巧
引言
PHP依然是Web开发的中坚力量,但性能问题常被忽视。本文将分享生产中验证的高效技巧,助你显著提升应用速度。
1. OPcache:必启用的字节码缓存
避免每次请求编译脚本,性能提升3倍以上:
// php.ini 配置
opcache.enable=1
opcache.memory_consumption=128 // 分配128MB内存
opcache.validate_timestamps=0 // 生产环境关闭时间戳验证
2. 避免循环中的SQL查询
用单次查询+数组处理替代N+1查询:
// 反例:循环内查询
foreach ($userIds as $id) {
$user = $db->query("SELECT * FROM users WHERE id = $id");
// ...
}
// 正解:单次查询
$users = $db->query("SELECT * FROM users WHERE id IN (".implode(',',$userIds).")");
$userMap = array_column($users, null, 'id'); // 转为ID为键的数组
3. 高效数组合并技巧
array_merge()在循环中性能差,改用+运算符:
$result = [];
foreach ($dataSets as $set) {
// 反例:每次循环创建新数组
// $result = array_merge($result, $set);
// 正解:直接追加
$result += $set;
}
4. 预编译语句提速数据库
重用预处理语句减少SQL解析开销:
$stmt = $db->prepare("SELECT * FROM orders WHERE user_id = ? AND status = ?");
$stmt->bind_param("is", $userId, $status);
// 循环中重复使用
foreach ($statuses as $status) {
$stmt->execute();
$orders = $stmt->get_result()->fetch_all();
}
结语
关键优化原则:
- 始终启用OPcache
- 用批量查询替代循环单查
- 大数据操作慎用
array_merge - PDO/MySQLi预处理防SQL注入