Home  >  Article  >  Backend Development  >  Briefly talk about PHP optimization_PHP tutorial

Briefly talk about PHP optimization_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 10:57:071012browse

When we write programs, we always want to make our programs take up the least resources, run faster, and have less code. Often we lose a lot of things while pursuing these. Next I would like to talk about my understanding of PHP Optimization. The purpose of optimization is to spend the least cost in exchange for the fastest running speed and the easiest to maintain code.

Carry out large-scale optimization instead of chewing on certain program codes

The optimization I am talking about here is basically from the server, Apache, database, etc. The optimization is based on aspects, rather than improving your PHP code to increase the running speed of the program, because compared to optimizing the regular expressions in the program into string processing functions to increase the speed of the program, it is carried out on a large scale. The cost of optimization is much smaller than this, but the reward is much richer.

Optimizing non-code areas has the following benefits:

1. Under normal circumstances, it can greatly improve efficiency

2. It will not endanger the integrity of the code

3. Ability to quickly deploy

Caching technology

Let’s talk about commonly used caching technologies. Through these caching technologies, efficiency can be greatly improved

When talking about caching technology, we have to mention memcached. Memcached is an efficient and fast distributed memory object caching system, mainly used to accelerate WEB dynamic applications.

Principle of Memcached

memcached runs in one or more servers as a daemon, waiting to receive connection operations from clients. Clients can be written in various languages Written (e.g. PHP). After clients such as PHP establish a connection with the memcached service, the next thing is to access objects. Each accessed object has a unique identifier key. Access operations are performed through this key and saved to memcached. The objects in are actually placed in memory, not stored in cache files, which is why memcached can be so efficient and fast.

After talking about memcached, let’s talk about commonly used caching methods

1. Compilation and OPCODE caching

Because PHP It is an interpreted language, so each PHP file needs to be compiled and then executed when running. If the same file is accessed by different users, or the same user accesses the same file at different times, it needs to be recompiled and run every time. , which consumes a lot of time.

By compiling and caching, each file is only compiled once after modification, which reduces file IO operations. After the user accesses, the machine instructions are directly fetched from the memory and executed instead of being read from the hard disk.

The most common PHP compilation caching tools are: APC, Accelerator, xcache

2. Global page cache--Squid Cache

Squid Cache (referred to as Squid) is a popular free software (GNU General Public License) proxy server and Web caching server. Squid serves as a front-end cache server for the web server to improve the speed of the Web server by caching related requests.

3. Local cache of SQL cache

In most applications, the main bottleneck can often be traced back to the operation of the database, usually because of the complex database Querying consumes a lot of time, and SQL caching can greatly reduce the load caused by complex queries.

Example of SQL cache (using memcached extension)

Code snippet:

<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>

4. Local cache code block cache

In order to optimize PHP programs, sometimes we have to optimize each code segment to reduce the execution time a little bit, but instead of optimizing different complex PHP code segments, it is better to ignore them directly through caching The advantages of optimizing these code segments are:

1. You can see the effect quickly

2. It will not destroy the previous code

3. Speed Much faster than optimizing code

Examples of code block caching (also using memcached extension)

Code snippet:

<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>

Of course in addition to the above methods You can use file caching (retrieving data from the database and storing it in a file), and you can also generate static HTML files, etc. However, the cache of these methods still stores the file on the hard disk instead of in the memory.

Output control

In addition to the above caching technology, you can also use output control to make the program execution time shorter

The following is done through PHP and APACHE Let’s talk about output control

1. PHP output control

The main ones used here are ob_start() and the OB series functions in PHP. What can these functions do?

The first is static template technology. The so-called static template technology uses a certain method to enable users to get the html page generated by PHP on the client side. If this HTML page will no longer be updated, then when another user browses this page again, the program will no longer call PHP and related databases. For some websites with a large amount of information, such as sina, 163, sohu. The benefits of technology like this are huge.

Code example:

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></li><li><span>ob_start(); </span><span class="comment">//打开缓冲区 </span><span> </span></li><li class="alt"><span>?>  </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,然后&hellip;&hellip; </span><span> </span></li><li class="alt"><span>fclose(</span><span class="vars">$fp</span><span>);  </span></li><li><span>?> </span></li>
</ol>

Of course, this ob series function has many other uses, which I won’t explain one by one here.

2. apache output control

Set SendBufferSize to the page size, so that the page can be placed in the send buffer at once to increase processing speed.
SendBufferSize command

Description: TCP send buffer size (bytes)

Syntax: SendBufferSize bytes

Default value: SendBufferSize 0

Function Domain: server config

Status: MPM

Module: beos, mpm_netware, mpm_winnt, mpmt_os2, prefork, worker

This command sets the size of the server's TCP send buffer ( byte). Increasing this value will lead to two consequences: high speed and high latency (around 100ms). If set to "0", the operating system default will be used.

Compiling your Apache/PHP/Database through source code can increase the speed of your program by 10-15%

The following will talk about what you should pay attention to when optimizing the code.

1. Short code does not equal fast code

Many people hope to write the code as concisely as possible when writing programs, but shorter code sometimes requires Longer execution time, so even if you use more code, don’t use slow code

2. When writing a program, you should pay more attention to the scalability of the program instead of pursuing speed

3. Before optimizing your code, first look at the parts related to the database, because the bottleneck of most applications is the database rather than the code

4. Micro-optimization is not worth the gain

What Called micro-optimization? As mentioned before, replace the regular expression part of the code with string functions. This has the following disadvantages:

(1) It takes longer

(2) It will not solve your performance problem

(3) It is very likely to destroy the previous The code thus produces unknown errors

(4) The effort exceeds the reward

There is also a misunderstanding that I have to mention here. In order to make the program more optimized, some people will analyze the business logic when analyzing the business logic. Optimizations are taken into account, thereby changing the business logic in order to get better code. This is a very stupid idea, because the purpose of the program is to solve problems encountered in reality and to serve these problems. How can it put the cart before the horse?


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445802.htmlTechArticleWhen we write programs, we always want to make our programs take up the least resources and run faster. The amount is less. Often we lose a lot of things while pursuing these. Next...
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