fibonacci

JavaScript performance comparison

Test case created by Kristof Neirynck

Preparation code

<script>
  var index = 20;
  var r5 = Math.sqrt(5);
  var phi = (1 + r5) / 2;
  
  function fibonacci_recursive(n) {
    if (n < 2) return n;
    return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1);
  }
  
  function fibonacci_loop(n) {
    if (n < 2) return n;
    var previous = 0;
    var current = 1;
    var next;
    for (var i = 1; i < n; i++) {
      next = previous + current;
      previous = current;
      current = next;
    }
    return current;
  }
  
  function fibonacci_direct(n) {
    if (n < 2) return n;
    return (Math.pow((1 + r5) / 2, n) - Math.pow((1 - r5) / 2, n)) / r5;
  }
  
  function fibonacci_direct2(n) {
    if (n < 2) return n;
    var r5 = Math.sqrt(5);
    var phi = (1 + r5) / 2;
    return (Math.pow((1 + r5) / 2, n) - Math.pow((1 - r5) / 2, n)) / r5;
  }
  
  function fibonacci_round(n) {
    if (n < 2) return n;
    return Math.round(Math.pow(phi, n) / r5);
  }
  
  function fibonacci_round2(n) {
    if (n < 2) return n;
    var r5 = Math.sqrt(5);
    var phi = (1 + r5) / 2;
    return Math.round(Math.pow(phi, n) / r5);
  }
</script>
    

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
recursive
var result = fibonacci_recursive(index);
pending…
loop
var result = fibonacci_loop(index);
pending…
direct
var result = fibonacci_direct(index);
pending…
round
var result = fibonacci_round(index);
pending…
direct2
var result = fibonacci_direct2(index);
pending…
round2
var result = fibonacci_round2(index);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments