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 开发者_如何学Go(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.
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.
精彩评论