TCO for fibonacci

JavaScript performance comparison

Revision 4 of this test case created by gfx

Info

"loop" is a hand-optimized version of fibonacci. "recursion" is a tail-recursion. "tco" (tail-call-optimization) is a machine-translated version of "recursion".

Preparation code

`` <script>  Benchmark.prototype.setup = function() {    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 \$a, \$b, \$c;            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 unknown unknown
Test Ops/sec
loop
``fib_loop(n)``
pending…
recursion
``fib_rec(n)``
pending…
tco
``fib_tco(n)``
pending…

Revisions

You can edit these tests or add even more tests to this page by appending `/edit` to the URL. Here’s a list of current revisions for this page: