by toolslive · 5y ago · 0 comments
<?php
function fib($n)
{
if($n === 0) { return 1;}
if($n === 1) { return 1;}
$r = fib($n-1) + fib($n-2);
return $r;
}
$n= (int) $argv[1];
$r = fib($n);
printf("%d %d\n",$n,$r);
just did some measurements on my laptop: | Language | n | time(s) |
|----------------------+----+---------|
| php (7.4.25) | 42 | 422.0 |
| python3 | 42 | 90.0 |
| haskell (ghc -O3) | 42 | 13.8 |
| f# | 42 | 5.6 |
| ts | 42 | 2.8 |
| ocaml (ocamlopt -O3) | 42 | 0.98 |
| C (gcc -O3) | 42 | 0.66 |
(edit: added php version in table. ) time php fib.php 42
23s
time python3 fib.py 42
1m1s
I suspect that you're doing something very wrong, like running PHP with an active debugger or similar.If we're talking in comparison to slow interpreted languages like Python, then function calls in PHP are not particularly expensive. Debuggers can make them quite expensive though.
Edit: Just to note, PHP's execution time drops to 4s with enabled JIT.
Something doesn't quite add up across everyone's results here, but the extremely slow result at the top of the thread is almost certainly a debugger slowing things down.
Edit: I was missing `opcache.jit_buffer_size`, and saw the runtime drop to under ten seconds with that correctly configured.
Yes this is a microbenchmark. Yes, I know binet's formula... Yes it's weird function calls are so slow in php.
with php 8.0 (jit enabled) you get something like 120s (for n= 42)
Microbenchmarks are meaningful as long as one doesn't read too much from them. This benchmark shows that PHP seems to have a problem with recurrent calls.