1

I wrote three javascript functions which works the same task. They all provide the same result but I am wondering which one of them is faster and most scalable?

Here are my functions first one

function odds(n, p) {
    var acc = 1;
    for (var i = 0; i < n; i++) {
        acc *= (n - i) / (p - i);
    }
    return acc;
}

second one

function odds(n, p) {
    if (n == 0) {
        return 1;
    } else {
        return (n / p) * odds(n - 1, p - 1);
    }
}

third one

var odds = (function () {
    var odds1 = function(n, p, acc) {
        if(n == 0) {
            return acc;
        } else {
            return odds1(n - 1, p - 1, (n / p) * acc);
        }
    }
    return function(n, p) {
        return odds1(n, p, 1);
    }  
}());
uzyn
  • 6,625
  • 5
  • 22
  • 41
Om3ga
  • 30,465
  • 43
  • 141
  • 221

3 Answers3

3

you can use http://jsperf.com/ to test javascript performance so that you can know which function is faster

Dorsey
  • 854
  • 3
  • 9
  • 17
3

You must test to answer questions like this, but it's also generally true that an internal loop is nearly always faster than recursion in javascript. Test harnesses like jsPerf can be very, very helpful for giving you real data.

I built a jsPerf for your three cases here: http://jsperf.com/oddsflavors. For the parmeters I picked (I wasn't sure what parameters would be most important to you), it shows your first code option (the one without recursion) to be about twice as fast as the second one.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

You can use various tools to test the speed of your Javascript code, such as JSLitmus and jsPerf.

Also, check out this question: How do you performance test JavaScript code?
And this article on Javascript performance testing.

Community
  • 1
  • 1
jeff
  • 8,300
  • 2
  • 31
  • 43