TCO for fibonacci

JavaScript performance comparison

Test case created by gfx

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;
    }
   
    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(100)
pending…
recirsion
fib_rec(100)
pending…
tco
fib_tco(100)
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. Here’s a list of current revisions for this page:

0 comments

Add a comment