With Pear::benchmark, you already know how to test your code, know how to judge if your code is fast or slow, and which part of it is slower. So the next thing I want to say is how to eliminate or optimize that part of the slow code.
My personal main experience at this point is only two points, one is to eliminate the wrong or inefficient cycle; the second is to optimize the database query statement. In fact, there are some other optimization details, such as "Str_replace faster than Ereg_replace", "Echo is faster than print" and so on. I'll put these aside for a while, and I'll mention using caching to deal with too-frequent IO.
Here we will compare the efficiency of the three functions with different functions (the time consumed).
Badloops. Php
<?php
Require_once (' benchmark/iterate.php ');
Define (' Max_run ', 100);
$data = Array (1, 2, 3, 4, 5);
Dobenchmark (' v1 ', $data);
Dobenchmark (' v2 ', $data);
Dobenchmark (' v3 ', $data);
function Dobenchmark ($functionName = null, $arr = NULL)
{
Reset ($arr);
$benchmark = new Benchmark_iterate;
$benchmark->run (Max_run, $functionName, $arr);
$result = $benchmark->get ();
Echo ' <br> ';
printf ("%s ran%d times where average exec time%.5f MS",
$functionName, $result [' iterations '], $result [' mean '] * 1000);
}
function V1 ($myArray = null) {
Inefficient cycle
for ($i =0; $i sizeof ($myArray); $i + +)
{
Echo '!--'. $myArray [$i]. '--> ';
}
}
Function v2 ($myArray = null) {
A slight increase in efficiency
$max = sizeof ($myArray);
for ($i =0; $i $max; $i + +)
{
Echo '!--'. $myArray [$i]. '--> ';
}
}
function v3 ($myArray = null) {
Best efficiency
echo "!--", Implode ("-->!--", $myArray), "-->";
}
? >
The result of the program output is probably this:
V1 ran where average exec time 0.18400 ms
V2 ran where average exec time 0.15500 ms
V3 ran where average exec time 0.09100 ms
As you can see, the execution time of the function becomes less and the efficiency is increased.
The function v1 has a very obvious error, each time of the loop, you need to call the sizeof () function to calculate. The function v2 the number of elements in the $myarray array outside the loop to the $max variable, avoiding the need to compute the number of elements of the array for Each loop, so the efficiency is increased. Function V3 is the most efficient, using ready-made functions to avoid loops.
This example just gives you a perceptual understanding of what is relatively efficient code. In the actual development, I believe many people will be stumbled to write a lot of inefficient code. To write code in a concise and efficient way, I'm afraid it takes time to temper:-) But this is another topic, we skip it.
database application basically every PHP program will be used, in the actual development I found that the most impact on the efficiency of the entire system is the database part.