TCO for fibonacci

JavaScript performance comparison

Revision 6 of this test case created by gfx

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  "use strict";
  
  var n = 2;
  
  function fib_rec_(n, a, b) {
      switch (n) {
      case 0:
      case 1:
          return a;
      default:
          return fib_rec_(n - 1, a + b, a);
      }
  }
  
  function fib_rec(n) {
      return fib_rec_(n, 1, 0);
  }
  
  function fib_tco_(n, a, b) {
      $TAIL_REC: while (true) {
          var $n, $a, $b;
          switch (n) {
          case 0:
          case 1:
              return a;
          default:
              $n = n - 1, $a = a + b, $b = a;
              n = $n, a = $a, b = $b;
              continue $TAIL_REC;
          }
      }
  }
  
  function fib_tco(n) {
      return fib_tco_(n, 1, 0);
  }
  
  function fib_loop(n) {
      if (n <= 2)
          return 1;
      var value = 1;
      var prevValue = 1;
      for (var i = 3; i <= n; i++) {
          var t = value + prevValue;
          prevValue = value;
          value = t;
      }
      return value;
  }
  
  if (fib_loop(10) !== fib_rec(10)) {
      throw new Error("oops!");
  }
  

};
</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
loop
fib_loop(n)
pending…
recursion
fib_rec(n)
pending…
tco
fib_tco(n)
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