PHP 性能优化:从代码到服务器的 6 个实用技巧

分类:后端开发 时间:2026-02-24 浏览:1
1

一、代码层面优化

1. 减少不必要的函数调用和循环
// 优化前:循环中调用count(),每次都计算数组长度
$arr = range(1, 1000);
for ($i = 0; $i < count($arr); $i++) {
    // 业务逻辑
}

// 优化后:提前计算长度
$length = count($arr);
for ($i = 0; $i < $length; $i++) {
    // 业务逻辑
}
2. 选择高性能的函数
// 优化前:array_key_exists()判断键是否存在(慢)
$arr = ['name' => '张三'];
if (array_key_exists('name', $arr)) {
    // 逻辑
}

// 优化后:isset()判断(快3倍+)
if (isset($arr['name'])) {
    // 逻辑
}

注意:isset () 会忽略值为 null 的键,若需判断 null 值,仍用 array_key_exists ()。

3. 避免嵌套过深的条件判断
// 优化前:嵌套4层if
if ($user['status'] == 1) {
    if ($user['role'] == 'admin') {
        if ($user['age'] >= 18) {
            if ($user['is_vip']) {
                // 逻辑
            }
        }
    }
}

// 优化后:提前return,扁平化逻辑
if ($user['status'] != 1) return;
if ($user['role'] != 'admin') return;
if ($user['age'] < 18) return;
if (!$user['is_vip']) return;
// 核心逻辑

二、缓存层面优化

1. Redis 缓存高频查询结果
<?php
// 封装缓存工具类
class Cache
{
    private static $redis;

    public static function init()
    {
        self::$redis = new Redis();
        self::$redis->connect('127.0.0.1', 6379);
        self::$redis->auth('your_redis_password'); // 有密码则添加
    }

    // 获取缓存,不存在则查询数据库并缓存
    public static function get($key, $expire = 3600, $callback = null)
    {
        $data = self::$redis->get($key);
        if ($data !== false) {
            return json_decode($data, true);
        }
        // 回调函数查询数据库
        $data = $callback();
        self::$redis->setex($key, $expire, json_encode($data));
        return $data;
    }

    // 删除缓存
    public static function del($key)
    {
        self::$redis->del($key);
    }
}

// 使用示例
Cache::init();
// 获取商品列表(缓存1小时)
$goodsList = Cache::get('goods_list', 3600, function () {
    $pdo = new PDO("mysql:host=localhost;dbname=php_demo;charset=utf8", "root", "");
    $stmt = $pdo->query("SELECT * FROM goods");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
});
print_r($goodsList);
?>
2. 开启 OPcache

OPcache 是 PHP 内置的字节码缓存扩展,能将 PHP 脚本编译后的字节码缓存到内存,避免每次请求都重新编译:

  1. 修改php.ini配置:

opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
  1. 重启 PHP-FPM:systemctl restart php-fpm

三、数据库层面优化

1. 慢查询日志分析

开启 MySQL 慢查询日志,定位耗时 SQL:

  1. 修改my.cnf配置:

ini

slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1 # 执行时间超过1秒的SQL记录
  1. 重启 MySQL:systemctl restart mariadb

  2. 使用mysqldumpslow分析慢日志:

# 查看最慢的10条SQL
mysqldumpslow -s t -t 10 /var/log/mysql/slow.log
2. 优化 SQL 与索引
-- 优化前:无索引,全表扫描
SELECT * FROM users WHERE email = 'test@demo.com';

-- 优化后:创建索引
CREATE INDEX idx_users_email ON users(email);

-- 避免SELECT *,只查需要的字段
SELECT id, username, email FROM users WHERE email = 'test@demo.com';

-- 避免使用LIKE %xxx(无法使用索引)
-- 优化:使用全文索引(适用于模糊查询)
ALTER TABLE goods ADD FULLTEXT INDEX idx_goods_name(name);
SELECT * FROM goods WHERE MATCH(name) AGAINST('手机');

四、服务器层面优化

1. PHP-FPM 配置优化

修改php-fpm.d/www.conf

pm = dynamic
pm.max_children = 50 # 最大子进程数(根据服务器CPU核心数调整,如8核设为40-60)
pm.start_servers = 10 # 启动时的进程数
pm.min_spare_servers = 5 # 最小空闲进程数
pm.max_spare_servers = 20 # 最大空闲进程数
pm.max_requests = 1000 # 每个进程处理1000个请求后重启,避免内存泄漏

重启 PHP-FPM:systemctl restart php-fpm

2. Nginx 静态资源缓存

修改 Nginx 配置:

server {
    listen 80;
    server_name demo.com;
    root /var/www/html;

    # 静态资源缓存(图片/JS/CSS)
    location ~* \.(jpg|jpeg|png|gif|css|js)$ {
        expires 7d; # 缓存7天
        add_header Cache-Control "public, max-age=604800";
        proxy_cache_bypass $http_pragma;
        proxy_cache_revalidate on;
    }
}

重启 Nginx:systemctl restart nginx

文章链接:http://www.qwkf.cn//houduan/24.html
文章标题:PHP 性能优化:从代码到服务器的 6 个实用技巧

相关阅读