iterative vs. recursive-fib-sum

JavaScript performance comparison

Test case created by Christof Kälin

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
iterative
function sumFibs(num) {
    let prevNumber = 0;
    let curNumber = 1;
    let result = 0;

    while (curNumber <= num) {
        if (curNumber % 2 !== 0) {
            result += curNumber;
        }
        curNumber += prevNumber;
        prevNumber = curNumber - prevNumber;
    }
    return result;
}
console.log(sumFibs(1000)); // 1785
pending…
recursive
const sumFibs = (() => {
    const o = { p: 0, c: 1, r: 0 };
    const d = Object.assign({}, o);

    const sumFibs = n => {
        if (o.c >= n) {
            const t = o.r;
            Object.assign(o, d);
            return t;
        }
        
        if (o.c % 2 !== 0)
            o.r += o.c;
        
        o.c = o.c + o.p;
        o.p = o.c - o.p;
        
        return sumFibs(n);
    }
    
    return sumFibs;
})();

console.log(sumFibs(1000)); // 1785
pending…

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

0 Comments