jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
This test demonstrates the expressive power of closures. It is not written for pure performance comparison! In fact, caching the results when computing even larger fibonacci numbers, will be zillion times faster.
Caching of intermediate results could be achieved through other means, e.g. polluting the global namespace with an array, that your function uses for caching. But closures are an elegant way to tie some internal state to a function, that resides over all invocations.
<script>
var fib_plain = function (n) {
return (n <= 1) ? n :
fib_plain(n - 2) + fib_plain(n - 1);
},
fib_closure = function () {
var cache = [];
return function (n) {
return (cache[n]) ? cache[n] :
(n <= 1) ? n :
(cache[n] = arguments.callee(n - 2) + arguments.callee(n - 1))
};
},
fib_closure_2 = function () {
var cache = [];
var f = function (n) {
return (cache[n]) ? cache[n] :
(n <= 1) ? n :
(cache[n] = f(n - 2) + f(n - 1))
};
return f;
},
fib_closure_3 = function () {
var cache = [0, 1];
var exist;
var f = function (n) {
if ((exist = cache[n]) != undefined) {
return exist;
}
return (cache[n] = f(n - 2) + f(n - 1))
};
return f;
},
fib_closure_4 = function () {
var cache = [0, 1];
var l = 1;
var f = function (n) {
if (n <= l) {
return cache[n];
}
for (l; l <= n; l++) {
cache[l] = cache[l-1] + cache[l-2]
}
return cache[n];
};
return f;
};
</script>
Ready to run.
Test | Ops/sec | |
---|---|---|
Plain Recursion |
| ready |
Closure Caching |
| ready |
Closure Caching 2 |
| ready |
Closure Caching 3 |
| ready |
Closure Caching 4 |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.