Originally I was testing out how adding some codes that caches the result will impact the initial calculation time. I create a simple recursive function that calculates factorials:
function fac(n){
return n <= 1 ? 1 : fac(n-1) * n;
}
Then I add the part that caches the result for later use:
var f = [];
function fac(n){
return n <= 1 ? 1 : f[n] ? f[n] : f[n] = fac(n-1) * n;
}
I put them in jsPerf and the result is that the version with cache is unexpectedly faster. I suspect it might be because the array f
I used remain the same in the test runner. The function was just grabbing the value from the array and thus it was faster.
To test I created another function that only returns the value from an array:
var test = []; test[10] = 3628800;
function control(n){
return n <= 1 ? 1 : test[n] ? test[n] : 1;
}
The result says the control is significantly faster than the function with caching added. So that concludes that either the following:
The array
f
is remain untouched and the difference in ops/sec is caused by the initial calculation.The array
f
is being "reset" each time and for some reason it is faster than the normal version.
I don't believe the initial calculation would make the whole test 74% slower than the control, therefore #2 should be true. But what makes it faster than the normal version? From 15,262,318 ops/sec to 114,370,808 ops/sec it's quite significant actually.