# TCO for fibonacci

## JavaScript performance comparison

Revision 3 of this test case created by gfx

## Info

"loop" is a hand-optimized version of fibonacci. "recursion" is a tail-recursion, which may be optimized by the JS engine. "tco" (tail-call-optimization) is a machine-translated version of "recursion". "simple recursion" uses recursive calls which will never be optimized by the JS engine

## Preparation code

`` <script>  Benchmark.prototype.setup = function() {    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;    }    function fib_simple_rec(n) {        return n <= 2 ? 1 : fib_simple_rec(n - 1) + fib_simple_rec(n - 2);    }        if (fib_loop(10) !== fib_rec(10)) {        throw new Error("oops!");    }    if (fib_tco(10) !== fib_simple_rec(10)) {        throw new Error("oops!");    }        var n = 30;  };</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…
simple recursion
``fib_simple_rec(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: