Saturday, March 14, 2009

Memoization with Javascript

Memoization is somewhat common optimization where the results of a function are cached, so that subsequent calls to that same function, with the same arguments can skip the execution and return the object from cache. With interpreted languages, the savings of memoizing frequently called funcitons with a limited domain of arguments can save quite a bit of execution time. Obviously, you need to balance this speed with the amount of memory that your page will consume. Finding DOM objects is a pretty good application of memoization.


function memoize(obj, func) {
the_func = obj[func];
cache = {};

return function() {
var key = Array.prototype.join.call(arguments, '_');
if (!(key in cache))
cache[key] = the_func.apply(obj, arguments);
return cache[key];
}
}

var ElementFinder = {
findById: function(id) {
console.log('Calling Function with id: %s', id);
return document.getElementById(id);
}
}

ElementFinder.findById = memoize(ElementFinder, 'findById');

function load() {
for(var i=0;i<10;i++) {
console.log(ElementFinder.findById('my_div').id);
}
}