by this question: Does PHP optimize tail recursion?
php will not optimize the tail recursion
but when I try on my machine, (php 5.3.10)
two programs for fibonacci: one is normal recursion, another is tail recursion
the time programs used differs a lot:
and I feel confused about that, who can tell me why the tail recursion is faster then normal recursion, if php does not optimize it?
fibonacci.php:
<?php
function fibonacci($n) {
if ($n < 2) {
return $n;
}
return fibonacci($n - 1) + fibonacci($n - 2);
}
var_dump(fibonacci(30));
fibonacci2.php:
<?php
function fibonacci2($n, $acc1, $acc2) {
if ($n == 0) {
return $acc1;
}
return fibonacci2($n-1, $acc2, $acc1 + $acc2);
}
var_dump(fibonacci2(30, 0, 1));