Fibonacci - Plain Recursion vs. Closure Caches

Benchmark created by Rob on


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.

Preparation HTML

  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))

Test runner

Ready to run.

Testing in
Plain Recursion
Closure Caching
// we need to create a new closure everytime


You can edit these tests or add more tests to this page by appending /edit to the URL.