PHP program acceleration exploration [6] - code optimization

xiaoxiao2021-03-06  94

<2> Acceleration

◆ Code optimization

Master Pear :: Benchmark, now you know how to test your code, know how to judge your code is slow, which part is slower. So, what I want to say is how to eliminate or optimize the slow code.

At this point, I have only two most important experiences, one is to eliminate erroneous or inefficient loops; the other is to optimize the database query statement. In fact, there are some other optimization details, such as "str_replace than EREG_REPLACE", "Echo is fast" than Print, etc. These I have been putting on one side, I will mention the use of caching to deal with too frequent IO.

Below we will identify the three functions, but the efficiency of different functions (time consumption time) is compared.

Badloops.php

Run (MAX_Run, $ FUNCTIONNAME, $ ARR); $ Result = $ Benchmark-> get (); echo '
'; Printf ("% s Ran% D Times where Average EXEC TIME% .5F MS", $ FunctionName, $ Result ['ITerations'], $ Result ['mean'] * 1000);} Function V1 ($ myarray = null) {// efficient cycle for ($ I = 0; $ i ';}}

Function V2 ($ MyArray = null) {// efficiency has increased $ max = sizeof ($ myarray); for ($ I = 0; $ I <$ max; $ i ) {echo '';}} Function V3 ($ MyArray = NULL) {// Best Efficiency Echo " ";}?>

The result of the program output is probably:

V1 RAN 100 Times Where Average EXEC TIME 0.18400 MS V2 RAN 100 Times Where Average Exec Time 0.15500 MS V3 RAN 100 Times Where Average Exec Time 0.09100 MS

It can be seen that the execution time of the function is less, and the efficiency is increased. The function V1 has a significant error, and each cycle requires calls the sizeof () function to calculate. The function V2 stores the element of the $ myarray array to the $ max variable outside the loop, avoiding the number of elements of the array every cycle, so efficiency is improved. The function V3 is the highest, and the ready-made functions are used to avoid cycling.

This example is only given you a sense of understanding, understand what is a relatively efficient code. In actual development, I believe there will be many people will be fascinated by many low efficiency code. To write the code, it is very efficient, I am afraid it takes time to hammered :-) But this is another topic, we have not talked.

Database applications Basically each PHP program will be used, I found that the most influential efficiency is the database in actual development. As for the optimization of the database and the optimization of the data query statement, it is limited to discussions in detail. You can see these two articles:

http://www.phpe.net/articles/340.shtml

http://www.phpe.net/articles/323.shtml

And this discussion:

Http://club.phpe.net/index.php?s==st=st&f=15&t=4783&st=0

(The previous post is good)

Mainly for mysql.

转载请注明原文地址:https://www.9cbs.com/read-123784.html

New Post(0)