3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * Various methods of computing Fibonacci numbers in PHP */ class Fibonacci { /** * @var array Memoization cache * @see Fibonacci::memoized */ protected $cache = array(0 => 0, 1 => 1); /** * Fibonacci using recursion */ public function recursive($n) { if ($n == 0) { return 0; } if ($n == 1) { return 1; } return $this->recursive($n - 1) + $this->recursive($n - 2); } /** * Fibonacci using an iterative approach */ public function iterative($n) { $a = 0; $b = 1; for ($i = 0; $i < $n; $i++) { $c = $a; $a = $b; $b += $c; } return $a; } /** * Fibonacci using Binet's formula * @link http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html */ public function binet($n) { $phi = (1 + sqrt(5)) / 2; return (pow($phi, $n) - pow(1 - $phi, $n)) / sqrt(5); } /** * Fibonacci using a cache */ public function memoized($n) { if (!isset($this->cache[$n])) { $this->cache[$n] = $this->memoized($n - 1) + $this->memoized($n - 2); } return $this->cache[$n]; } } /** * Test each Fibonacci method and output the speed */ function test($total, $callback) { echo $callback[1] . ":\n"; $t = microtime(true); for ($x = 0; $x < $total; $x++) { call_user_func($callback, $x); } $finish = microtime(true) - $t; echo ($finish * 1000) . ' ms (' . (($finish / $total) * 1000) . ")\n\n"; } // You can pass in the total number of sequences to calculate as a CLI argument $total = isset($argv[1]) ? $argv[1] : 25; $fib = new Fibonacci(); test($total, array($fib, 'iterative')); test($total, array($fib, 'binet')); test($total, array($fib, 'memoized')); // Limit our attempts with recursion if ($total <= 30) { test($total, array($fib, 'recursive')); }

preferences:
32.39 ms | 402 KiB | 5 Q