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);
}
}());
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.