search
HomeBackend DevelopmentPHP TutorialA brief discussion on how to improve the speed of PHP_PHP Tutorial

A brief discussion on how to improve the speed of PHP_PHP Tutorial

Jul 20, 2016 am 10:57 AM
phpgenerallyAdvantageusehowcaseimprovemaximumofspeedhigh speed

The biggest advantage of using PHP is fast speed. In general, PHP is always fast enough to support dynamic generation of Web content, and many times it is not even possible to find a faster method than it. However, when faced with huge visits, high-load applications, limited bandwidth, and various other factors that cause performance bottlenecks, you need to consider how to improve the performance of PHP.

1. Code optimization

Code optimization is not just about writing clean and clear code, but also simplifying the code to a certain extent. You can use Zend Optimizer to automatically help complete these tedious tasks. Zend Optimizer is available for free from Zend Technologies' website at http://www.zend.com/, but you must agree to its licensing agreement because it is not distributed under the GPL. Its principle is simple, that is, by detecting the intermediate code generated by the Zend engine and optimizing it to obtain higher execution speed.

After using Zend Optimizer, the execution efficiency of complex PHP source programs will be significantly improved immediately. The disadvantage is that the readability of the optimized code decreases, making code modification difficult.

The installation method of Zend Optimizer is very simple. Just download the relevant precompiled version according to the platform the user is using, add the following 2 lines of code to the php.ini file, and restart the web server:

<ol class="dp-c">
<li class="alt"><span><span>zend_optimizer.optimization_level=15   </span></span></li>
<li><span>zend_extension=″/path/to/ZendOptimizer.so″  </span></li>
<li class="alt"><span>zend_loader.enable=Off  </span></li>
</ol>

The additional third line of code is optional because disabling zend_loader will make the optimization faster. It should be noted that zend_loader can be disabled only when Zend Encoder Runtime is not used.

2. Use caching

If the size of the PHP program is large, then the way to improve the speed is to use caching. There are many caching solutions available, including Zend Cache, APC and Afterburner Cache.

The above are all "caching modules". The first time a PHP file is called, the cache module generates some intermediate code from the PHP source code and stores these intermediate codes in the memory of the web server. When these files are called later, the "compiled" code in memory can be used directly. This method can really improve the performance of the application, because it reduces disk access to a minimum (the code has been read and parsed), and the code runs directly in memory, making the server respond to requests much faster.

Of course, the caching module will also monitor changes in PHP source files and re-cache the page if necessary to prevent users from getting pages that are still generated by outdated PHP code. Because caching modules can significantly reduce the load on the server and improve the response efficiency of PHP applications, they are very suitable for websites with heavy loads.

Zend Cache is a commercial software developed by Zend Technologies. After the first run, the running speed of the PHP page will be greatly improved immediately, and the server will have more free resources. The disadvantage is that it is not free, but the price/performance ratio is still very high.

Afterburner Cache is a free caching module developed by Bware Technologies. The function is basically the same as Zend Cache, but it is not as good as Zend Cache in improving performance.

APC (Alternative PHP Cache) is another free caching module developed by Community Connect. The current version is 2.0.4 and can be obtained from http://pecl.php.net/package/APC. For product applications, its performance is very stable, and it can also greatly improve the speed of responding to requests.

3. Compress web page content

There is another important factor that affects the access speed of the site, and that is the download speed. The solution is to compress web content. For plain text content, HTTP compression technology can compress to less than 40% of the original size, providing more than 60% data transmission savings. Although the Web server will cause a slight increase in CPU usage due to compression, it can save a lot of network IO for transmission.

According to IETF specifications, most browsers support the use of gzip compression algorithm for content compression. In other words, you can use gzip to compress the web page content first, and then send it to the client browser. The browser will automatically decompress the data when receiving it, and then display the page. This process is completely transparent to users. Likewise, there are different methods for compressing the content of web pages.

Mod_gzip is an open source, standard Apache module, also called Internet content acceleration module. It can be compiled with Apache or used as a DSO. Compared with the ordinary browsing process, it can save about 40% of traffic. Mod_gzip can not only compress static content, such as HTML and XML, but also compress and transmit dynamically generated content, including SQL, Java, WML, VRML, etc., in real time on the server side. Its compression efficiency is amazing, generally 60 %~85%.

To compress the content of dynamic web pages, you can also use class.gzip to encode .php files. class.gzip compresses the content of web pages by calling some of its functions at the beginning and end of the PHP script. If the entire site requires such compression, these functions can be called in auto_prepend and auto_append in the php.ini file, but it will take up a certain amount of system overhead.

PHP4.0.4推出了1种新的输出缓冲的处理手段—ob_gzhandler,它的作用和class.gzip完全一样,区别是可以直接把它加到php.ini 文件中,语法如下: 

<ol class="dp-c"><li class="alt"><span><span>output_handler = ob_gzhandler; </span></span></li></ol>

这样将激活PHP的输出缓冲功能,并在发送内容前进行压缩。如果不想在这里设置,只在需要的地方才改变这个默认设置(不压缩),只要在需要压缩的PHP源程序目录中,修改一下.htaccess文件就行了,语法如下: 

<ol class="dp-c"><li class="alt"><span><span>php_value output_handler ob_gzhandler  </span></span></li></ol>

或者直接在PHP代码中调用它:

<ol class="dp-c"><li class="alt"><span><span>ob_start(″ob_gzhandler″); </span></span></li></ol>

输出缓冲的效果确实很理想,并且不会为服务器带来额外的系统开销。要注意的一点是Netscape Communicator不支持图像的压缩。因此除非知道访问者都使用Internet Explorer,否则必须禁止压缩jpeg和gif图象。

4 其它技巧

在编程时,使用一些小技巧也可以加快PHP的运行速度:

(1)用i+=1代替i=i+1,既符合c/c++的习惯,效率相对还更高。

(2)尽可能使用PHP内部函数。

(3)能使用单引号字符串时,尽量使用单引号字符串。单引号字符串的效率要高于双引号字符串。

(4)用foreach代替while遍历数组,foreach的效率明显高于while循环,而且不需要调用reset函数。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445800.htmlTechArticle使用 PHP 的最大1个优势就是速度快。一般情况下,PHP总是具有足够的速度支持Web内容动态生成,许多时候甚至无法找出比它更快的方法。然...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment