← back to all talks and articles

Awesome Javascript memoization

Regular memoization

Here’s an easy way to memoize expensive Javascript functions. It introduces slightly obscure code and an extra function call, but if your operation is expensive enough to memoize, it is probably worth the extra overhead:

this.foo = function(){
    var foo = expensive_operation();
    return (this.foo = function() { return foo; })();

What this function does is redefine itself, so on subsequent calls it only returns a static value. Neat.

Argument-specific memoization

There is another way of memoizing expensive operations in Javascript, which is also fit for argument-specific results:

base._fooCache = {};
base.foo = function(arg) {
    if(base._fooCache[arg] === undefined) {
        base. _fooCache[arg] = ...expensive operation...
    return base. _fooCache[arg];

This just keeps a local key/value cache of the result of the expensive operation for the given argument. This only works for a single argument right now, but I guess it could be extended to multiple arguments.

  • code
  • javascript
Arjan van der Gaag

Arjan van der Gaag

A thirtysomething software developer, historian and all-round geek. This is his blog about Ruby, Rails, Javascript, Git, CSS, software and the web. Back to all talks and articles?


You cannot leave comments on my site, but you can always tweet questions or comments at me: @avdgaag.