提高PHP性能的方法

提高PHP性能的方法

下面的文字从Dustin Whittle的 Scaling PHP in the real world 摘抄而来。原文作于2013年,有些信息可能不是那么新了。 https://speakerdeck.com/dustinwhittle

性能的提高,对于高并发访问量的应用来说,至关重要。本文主要是对上文提到的各种方法进行进一步的解释。

Opcode Cache
后台用queue来处理工作 (doing work in the background with queues)
部署用HTTP caching (Varnish/Squid) 和反向代理缓存
分布式数据缓存: Memcached 或者 redis
采用合适的工具
Xdebug+ Valgrind + WebGrind
AppDynamics
重视架构

具体的小贴士:
* 升级到最新版本的PHP
* 用Nginx + PHP-FPM
* 使用opcode cache
  PHP是解释性语言,每次一个PHP页面请求处理的时候,服务器都需要解释PHP文件,编译成opcode,然后执行。 opcode 缓存把编译好的opcode保存到共享内存中,这样就避免了重复编译,减少了cpu的开销(对于瓶颈是cpu的应用来说,性能提升比较明显)。编译只需要在第一次请求的时候执行。多种方式可以做opcode 缓存: APC, Zend Opcache(https://pecl.php.net/package/ZendOpcache), XCache
 
* 使用自动加载, 避免了多require或者include的解析 spl_autoload_register()
    bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
* 优化会话, 把缺省的文件保存形式转为数据库保存,并用缓存起来(memcached, redis等)
  限制会话数据大小为4M,把所有的数据保存在一个cookie中。
* 利用好内存数据缓存。
    Doctrine ORM for PHP 有基于memcached 和redis的缓存机制。缓存可以是某个页面,应用的配置文件, 或者网络服务的响应。
     http://memcached.org/
     http://redis.io
     http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/caching.html
* 在后台用一个队列来处理阻塞性工作
    Resque for PHP https://github.com/chrisboulton/php-resque
    Gearman
    RabbitMQ
    Kafka
    Beanstalkd
    ZeroMQ
    ActiveMQ
    http://kamisama.me/2012/10/09/background-jobs-with-php-and-resque-part-2-queue-system/
    http://kamisama.me/2012/10/12/background-jobs-with-php-and-resque-part-4-managing-worker/
* 使用HTTP缓存
   用Varnish作为反向代理
   http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
   http://www.mnot.net/cache_docs/
*  优化你的框架
* 数据库 分片
× 学习如何分析PHP 代码,提高性能
    xdebug  http://xdebug.org/
    WebGrind https://github.com/jokkedk/webgrind
    XHprofi
    Appdynamic  http://appdynamics.com
    Valgrind  http://valgrind.org/info/tools.html#callgrind
    
资料来源
https://speakerdeck.com/dustinwhittle

原文地址:https://www.cnblogs.com/restart/p/4403822.html