I have 2 functions to calculate n! (factorial). The first is a recursive function, the second a straight loop. I have tested their performance in jsperf.com. For all browsers I tested the nonrecursive function outperforms the recursive one, except IE (tested for v7, 8 en 9). Now I'm very used to IE and jscript being the exception, but in this case I'm cursious: what could be the cause of the difference (in other words, if I want my factorial to be fast in every browser, must I really check for the browser first;)?
The functions used are:
//recursive
function factorial(n) {
var result = 1,
fac = function(n) {
return result *= n, n--, (n > 1 ? fac(n) : result);
};
return fac(n);
}
//nonrecursive
function factorialnr(n){
var r = n;
while (--n > 1) {
r *= r != n ? n : 1;
}
return r;
}
Probably because the browser is not able to optimize tail recursion. It doesn't realize that your lambda function to could be rewritten iteratively and eliminate the overhead of a function call.
Browsers aren't really meant to be fully fledged compilers and I wouldn't expect them to be able to perform all the optimizations that traditional compilers perform. If a certain browser can perform a particular optimization, that's great. But that doesn't mean all will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With