PHP array_combine & range VS foreach loop to get array of numbers -


i have been thinking this, code readability tend use php built in functions range & array_combine generate array of numbers this:

array(    5 => 5,    10 => 10,    15 => 15,    20 => 20,    25 => 25,    ...    60 => 60 ); 

so use generate above:

$nums = range(5, 60, 5); $nums = array_combine($nums, $nums); 

i wondering if there speed or memory difference between above approach , using loop this:

for ($i = 5; $i <= 60; $i++) {    $nums[$i] = $i;     $i += 5; } 

i want know if approach practice or if @ code try find out live?

the following method seems fast small numbers:

$tmp = range(5,$limit,5); $tmp = array_combine($tmp, $tmp); 

however, loop faster bigger numbers:

for($i =5; $i<=$limit; $i += 5)     $tmp[$i] = $i; 

try following code here:

 <?php $limit = 200;  $time_start = microtime(true); $tmp = range(5,$limit,5); $tmp = array_combine($tmp, $tmp); $time_end = microtime(true); echo  $time_end - $time_start; echo "<br/>"; //print_r($tmp); echo "<br/>";   $time_start = microtime(true); $tmp = array(); for($i =5; $i<=$limit; $i += 5)     $tmp[$i] = $i; $time_end = microtime(true); echo  $time_end - $time_start; echo "<br/>"; //print_r($tmp); 

for $limit = 200 first method faster:

1=> 2.0980834960938e-5 2=> 2.1934509277344e-5 

range & combination wins!

for $limit = 500 second method faster:

1=> 3.7908554077148e-5 2=> 2.9087066650391e-5 

for loop wins!

so in opinion, pick second method (for loop) since small number, if first method faster, time difference negligible. however, large numbers, second method faster, , care in computer science, worst time

conclusion:

for loop winner!


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -