Compact memoization comparisons (v3)

Revision 3 of this benchmark created by Nick McCready on


Description

A comparison of compact memoization routines providing the bare minimum functionality necessary for caching.

Preparation HTML

function fib(x) {
  if (x < 2) return 1;
  else return fib(x - 1) + fib(x - 2);
}

// compact memoizer
function memoize1(param) {
  this.memoize = this.memoize || {};
  return (param in this.memoize) ? this.memoize[param] : this.memoize[param] = fib(param);
}

// using an external cache
var memCache = {};

function memoize2(param, cache) {
  cache = cache || {};
  return (param in cache) ? cache[param] : cache[param] = fib(param);
}


// stoyan's memoizer
function memoize3(param) {
  if (!memoize3.cache) {
    memoize3.cache = {};
  }
  if (!memoize3.cache[param]) {
    var result = fib(param); //custom function
    memoize3.cache[param] = result;
  }
  return memoize3.cache[param];
}

//latest gratest sept 9th 2014 memoize.js
var memoize4 = function(func) {
  var stringifyJson = JSON.stringify,
    cache = {};

  var cachedfun = function() {
    var hash = stringifyJson(arguments);
    return (hash in cache) ? cache[hash] : cache[hash] = func.apply(this, arguments);
  };

  cachedfun.__cache = (function() {
    cache.remove || (cache.remove = function() {
      var hash = stringifyJson(arguments);
      return (delete cache[hash]);
    });
    return cache;
  }).call(this);

  return cachedfun;
};

var m1, m2, m3, m4 = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
Compact memoize.js
m1 = memoize1(10);

setTimeout(function() {
  m1 = memoize1(10);
}, 1000);
ready
Stoyan's version
m3 = memoize3(10);

setTimeout(function() {
  m3 = memoize3(10);
}, 1000);
ready
With external cache
m2 = memoize2(10, memCache);

setTimeout(function() {
  m2 = memoize2(10, memCache);
}, 1000);
ready
memoize.js
m4 = memoize4(10);

setTimeout(function() {
  m4 = memoize4(10);
}, 1000);
ready

Revisions

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

  • Revision 1: published by Addy Osmani on
  • Revision 2: published on
  • Revision 3: published by Nick McCready on
  • Revision 4: published by Nick McCready on
  • Revision 5: published by yespeter on