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;
}
I have looked further but couln’t find anything on the subject. After testing it seems that removing the ternary in version 1 of the jsperf test made IE behave like other browsers (see rev 5 of the jsperf-test). But testing for the ternary on it’s own didn’t really show differences.
Well, let’s leave it to that. What I’ve learned here is that it’s advisable to see if a recursive function can be rewritten in an iterative way. The latter seems to outperform recursion.
Thanks for your answers, appreciated it.