PHP

Recursion vs Iteration

  
  • Favourite
Average Star Rating is 3 from the Total 6 Ratings


Copy and try this code in phpfiddle and press run.


 

<?php
    $st = microtime(true);
    $et =0;
    $_function =0;
    $_loop = 0;
## Using recursion  ##   
function count_val($val){
   global $st, $_function;
    if($val<=10){
       echo $val++."..";
       count_val($val);
    } else {
       echo "<br>DONE<br>";
       $_function = microtime(true) - $st;
       echo $_function;
       echo "<hr />";
    }
}
## Using iteration (for loop) ##
for($i=1;$i<=10;$i++){
    echo $i."..";
    $_loop = microtime(true)-$st;
}
count_val(1);
echo "<br />";
echo "LOOP: $_loop <br />";
echo "<br /><hr /> Result On Max Time<hr /><br />";
if($_function >$_loop ){
    echo "Recursion (function) took more time : $_function ";
}else {
    echo "Iteration (loop) took more time: $_loop ";
}
?>

               *------RESULT------*

1..2..3..4..5..6..7..8..9..10..1..2..3..4..5..6..7..8..9..10..

DONE

8.2015991210938E-5

LOOP: 6.0081481933594E-5 

Result On Max Time

Recursion (function) took more time : 8.2015991210938E-5


Be the first to make a comment!