I did up 2 versions of a factorial function in PHP for benchmarking, one using normal recursion, the other using tail recursion. The latter should be faster but results show otherwise. Am I missing anything here?
My code is as follows, including the benchmark test:
<?php
benchmark();
function benchmark()
{
$n = 10;
$multiplier = 10000;
$functions = array('factorial_recursive', 'factorial_tailRecursive');
foreach ($functions as $function) {
$start = microtime(true);
echo $function . '<br>';
echo $function($n) . '<br>';
echo ($multiplier * (microtime(true) - $start)) . '<br><br>';
}
}
function factorial_recursive($n)
{
if ($n == 1) {
return $n;
}
return $n * factorial_recursive($n - 1);
}
function factorial_tailRecursive($n, $result = 1)
{
if ($n == 1) {
return $result;
}
return factorial_tailRecursive($n - 1, $result * $n);
}
Printed output:
factorial_recursive
3628800
2.4199485778809
factorial_tailRecursive
3628800
2.5296211242676
Any insight appreciated – thanks!
I took your code and modified it slightly for running on the command line (converted br’s to newlines, tweaked the output format). Also, I changed it so that benchmark is run for 25 iterations instead of just one:
Here is my php cli version:
Here are the results of my 25 iterations:
Looking at these results, I’d have to say the difference is negligible, too close to call. They’re effectively identical in runtime, at least in terms of Big-O.