Today, when I read the Arr class in the Kohana source code, I found this function
| The code is as follows |
Copy Code |
/**
* Fill an array with a range of numbers.
*
* //Fill a array with values 5, a,
* & nbsp $values = Arr::range (5, 20);
*
* @param integer $step stepping
* @param integer $ max ending number
* @return Array
*/
public static function range ($step = $max = 1
{
if ($step <)
return Arra Y ();
$array = Array ();
for ($i = $step; $i <= $max; $i = = $step)
&nb sp; {
$array [$i] = $i;
}
& nbsp; return $array;
} |
When I saw this, I found that PHP's original sound function can also achieve this function, and suddenly thought of a predecessor heard about PHP performance optimization of the argument--php provides us with so many of the original function, we try to use the original function to solve the problem. So I did a test to see how much faster PHP native function performance than I wrote. The function to be tested has the native function range () and the function _range (), where the underscore starts because the rewrite of the original sound function range () will error "Fatal Error:cannot redeclare range () in".
| code is as follows |
copy code |
function _range ($step = ten, $max = +)
{
if ($step < 1 )
return Array ();
$array = Array ();
for ($i = $step; $i <= $max; $i = = $step)
{
$array [$i] = $i;
}
return $array;
}
$time [' begin '] = Microtime (true);
$tmp = range (0,1000000,3);
//$tmp = _range (0,1000000,3);
$time [' End '] = Microtime (true);
Echo $time [' End ']-$time [' Begin ']. ' S '. ' R ";
Echo (Memory_get_peak_usage ()/1024/1024). M "; |
tested with both native and custom functions, resulting in a multiple of all 3 between 0~1000000, the result was unexpected:
First uses the result of a native function:
The following is the result of using a custom function:
To make the results more accurate, I'm doing a chart statistic
statistics times native function range () Custom Function _range ()
( 0,1000000,3) 5.155e-3s 27.5530M 1.907e-5s 0.1241M
(0,1000000,2) 7.479e-3s 40.2688M 1.811e-5s 0.1241M
(0,1000,1) 8.16e-5s 0.1620M 2.649e-5s 0.1241M
You can see from the table that custom functions save memory and time when random numbers are generated, and that native functions are particularly memory-consuming and time-consuming when generating a large number of random numbers, and the custom function in this aspect performance is good, produces the memory and consumes the time basically to be stable, looks the front that predecessor said is not necessarily completely correct, but here must notice our custom function can only generate the number, but the native range can also produce the letter, But I think it's not too hard to add a letter to this custom function ~
It seems Kohana official to range This function is very understanding, the PHP kernel in the complexity of the function is also very understanding, so this small optimization can do so well, too powerful!!!