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 =, '_');
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++) {


jaemeyeastwood said...

The casino?
What does the number 온라인 슬롯 of 사설토토 slots winrate 스포츠라이브스코어 increase? The majority of slots winrate is lower compared to others. This is because the slot game is generally Is there 브라 벗기 a good chance of winning on slots?How do slots 메이저벳 work in casinos?