Home php教程 php手册 简单说说PHP优化

简单说说PHP优化

Jun 13, 2016 am 11:13 AM
php optimization occupy exist us smallest program Simple write my own Talk about it resource run speed

我们在编写程序时,总是想要使自己的程序占用资源最小,运行速度更快,代码量更少。往往我们在追求这些的同时却失去了很多东西。下面我想讲讲我对PHP优化的理解。优化的目的是花最少的代价换来最快的运行速度与最容易维护的代码。

进行大范围的优化,而不是死啃某些程序代码

我这里所说的优化,基本上都是从服务器,Apache,数据库这些方面来进行的优化,而并不是对你的PHP代码加以改进从而提高程序的运行速度,因为比起你将程序中的正则优化为字符串处理函数从而提升程序速度来说,在大范围内进行的优化所需要的代价要比这个小的多,而获得报酬却要丰厚的多。

在非代码处进行优化有以下好处:

1、通常情况下能够大大提高效率

2、不会危及到代码的完整性

3、能够快速部署

缓存技术

下面来说说常用的缓存技术,通过这些缓存技术能够大大的提高效率

在说到缓存技术的时候不得不提到memcached ,memcached是高效、快速的分布式内存对象缓存系统,主要用于加速 WEB 动态应用程序。

Memcached的原理

memcached 是以守护程序方式运行于一个或多个服务器中,等待接收客户端的连接操作,客户端可以由各种语言编写(例如PHP)。PHP 等客户端在与 memcached 服务建立连接之后,接下来的事情就是存取对象了,每个被存取的对象都有一个唯一的标识符 key,存取操作均通过这个 key 进行,保存到 memcached 中的对象实际上是放置内存中的,并不是保存在 cache 文件中的,这也是为什么 memcached 能够如此高效快速的原因。

说完memcached,下面来说说常用的缓存方法

1、编译与OPCODE缓存

因为PHP是解释型的语言,所以每个PHP文件在运行的时候都需要编译后再执行,同一个文件,不同的用户访问,或者同一个用户不同时间访问同一个文件,每次都需要重新编译然后运行,这样就耗费了大量时间。

通过编译缓存每个文件在修改之后只编译一次这样就减少了文件IO操作,用户访问后机器指令直接从内存中取出并执行而不是硬盘中读出。

最常见的PHP编译缓存工具有:APC,Accelerator,xcache

2、全局页面缓存-- Squid Cache

Squid Cache(简称为Squid)是一个流行的自由软件(GNU通用公共许可证)的代理服务器和Web缓存服务器,Squid作为网页服务器的前置cache服务器通过缓存相关请求来提高Web服务器的速度。

3、局部缓存之SQL缓存

在大多数应用程序中主要的瓶颈往往可以追溯到数据库的操作中,一般都是因为复杂的数据库查询而耗费了大量时间,而SQL缓存可以大大降低复杂查询造成的负荷。

SQL缓存的例子(使用了memcached扩展)

代码片段:

<ol class="dp-c">
<li class="alt"><span><span class="vars">$key</span><span> = md5(“some sort of sql query”);  </span></span></li>
<li>
<span class="keyword">if</span><span> (!(</span><span class="vars">$result</span><span> = memcache_get(</span><span class="vars">$key</span><span>))) {  </span>
</li>
<li class="alt">
<span class="vars">$result</span><span> = </span><span class="vars">$pdo</span><span>->query(</span><span class="vars">$qry</span><span>)->fetchAll();  </span>
</li>
<li>
<span class="comment">// 缓存查询结果一小时 </span><span> </span>
</li>
<li class="alt">
<span>memcache_set(</span><span class="vars">$key</span><span>, </span><span class="vars">$result</span><span>, NULL, 3600);  </span>
</li>
<li><span>} </span></li>
</ol>
Copy after login

4、局部缓存之代码块缓存

为了优化PHP程序,有时候我们不得不优化一个个代码段来减少那么一点点的执行的时间,但是比起优化复杂的不同的PHP代码段还不如通过缓存来直接忽略这些代码段的优化,这样做的好处是:

1、能够很快的看到效果 

2、不会破坏以前的代码

3、速度要比优化代码要快得多

代码块缓存的列子(同样使用了memcached扩展)

代码片段:

<ol class="dp-c">
<li class="alt"><span><span class="keyword">function</span><span> complex_function_abc(</span><span class="vars">$a</span><span>, </span><span class="vars">$b</span><span>, </span><span class="vars">$c</span><span>) {  </span></span></li>
<li>
<span class="vars">$key</span><span> = </span><span class="keyword">__FUNCTION__</span><span> . serialize  </span>
</li>
<li class="alt"><span>(func_get_args());  </span></li>
<li>
<span class="keyword">if</span><span> (!(</span><span class="vars">$result</span><span> = memcache_get(</span><span class="vars">$key</span><span>))) {  </span>
</li>
<li class="alt">
<span class="vars">$result</span><span> = </span><span class="comment">//函数代码 </span><span> </span>
</li>
<li>
<span class="comment">// 储存执行结果1小时  </span><span> </span>
</li>
<li class="alt">
<span>memcache_set(</span><span class="vars">$key</span><span>, </span><span class="vars">$result</span><span>, NULL, 3600);  </span>
</li>
<li><span>}  </span></li>
<li class="alt">
<span class="keyword">return</span><span> </span><span class="vars">$result</span><span>;  </span>
</li>
<li><span>} </span></li>
</ol>
Copy after login

当然除了上述方法外还可以用到文件缓存(将数据库中的数据取出储存在文件中),还可以生成静态HTML文件等,但是这些方法的缓存还是将文件储存在硬盘上而不是内存中。

输出控制

除了上述缓存技术外还可以通过输出控制来让程序执行的时间更少

下面通过PHP与APACHE来说说输出控制

1、PHP输出控制

这里最主要用到ob_start()以及PHP中的OB系列函数,这些函数可以做什么呢?

第一就是静态模版技术。所谓静态模版技术就是通过某种方式,使得用户在client端得到的是由PHP产生的html页面。如果这个html页面不会再被更新,那么当另外的用户再次浏览此页面时,程序将不会再调用PHP以及相关的数据库,对于某些信息量比较大的网站,例如sina,163,sohu。类似这种的技术带来的好处是非常巨大的。

代码示例:

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></span></li>
<li>
<span>ob_start(); </span><span class="comment">//打开缓冲区 </span><span> </span>
</li>
<li class="alt"><span>?>  </span></li>
<li><span>php页面的全部输出  </span></li>
<li class="alt"><span>  </span></li>
<li>
<span class="vars">$content</span><span> = ob_get_contents(); </span><span class="comment">//取得php页面输出的全部内容 </span><span> </span>
</li>
<li class="alt">
<span class="vars">$fp</span><span> = </span><span class="func">fopen</span><span>(</span><span class="string">"output.html"</span><span>, </span><span class="string">"w"</span><span>); </span><span class="comment">//创建一个文件,并打开,准备写入 </span><span> </span>
</li>
<li>
<span>fwrite(</span><span class="vars">$fp</span><span>, </span><span class="vars">$content</span><span>); </span><span class="comment">//把php页面的内容全部写入output.html,然后…… </span><span> </span>
</li>
<li class="alt">
<span>fclose(</span><span class="vars">$fp</span><span>);  </span>
</li>
<li><span>?> </span></li>
</ol>
Copy after login

当然这个ob系列函数还有其他很多用处我就不在这里一一说明了。

2、apache输出控制

将SendBufferSize设置为页面大小,这样就能将页面一次性放在发送缓冲区从而增加处理速度。
SendBufferSize 指令

说明:TCP发送缓冲区大小(字节)

语法:SendBufferSize bytes

默认值:SendBufferSize 0

作用域:server config

状态:MPM

模块:beos, mpm_netware, mpm_winnt, mpmt_os2, prefork, worker

这个指令设置服务器的TCP发送缓冲区的大小(字节)。提高这个值会导致两个后果:高速度和高潜伏时间(100ms左右)。如果设置为"0",将使用操作系统默认值。

通过源代码方式编译你的Apache/PHP/Database 可让你的程序增加10--15%的速度

下面再说说在代码优化的时候应该注意的

1、短代码不等于快的代码

很多人在写程序时希望将代码写的越简洁越好,但是越短的代码有时候反而需要更长的执行时间,所以哪怕是用更多的代码也不使用速度慢的代码

2、在写程序的时候更应该注重程序的扩展性,而不是追求速度

3、在优化你的代码之前,先看看跟数据库有关的部分,因为大多数应用程序的瓶颈在数据库而不是代码

4、微优化得不偿失

什么叫做微优化?就像前面所说的将正则表达式部分的代码改用字符串函数代替。这样做有以下缺点:

(1)花费时间较长

(2)不会解决你的性能问题

(3)很有可能会破坏以前的代码从而产生未知的错误

(4)付出大于回报

这里还不得不提到一个误区,有些人为了让程序更加优化,在分析业务逻辑的时候便将优化考虑在内了,从而为了得到更优的代码而改动业务逻辑。这是十分愚蠢的想法,因为程序的目的便是为了处理现实中遇到的问题,是为这些问题服务的,怎么能本末倒置呢。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles