Caching inside a Javascript function

13 April 2013

When building a javascript library, it’s important to be careful with heavy calculations on the client side. That’s why the following caching pattern is really useful from time to time.

As you maybe know, functions are regular objects in Javascript, so they can contain properties. In fact, they do have properties and methods out-of-the-box. You can leverage this language feature by building caching into a function call pretty easily.

In the following example you see a Javascript function that does some heavy calculations and it saves the result into a property on the function itself. The next time this function is called with the same argument it will return the last calculated result without recalculation.

var myFunction = function (param) {
    myFunction.cache = myFunction.cache || {};
    if (!myFunction.cache[param]) {
        var result = {result: 'calculation for '+param};
        // .. expensive calculation ..
        myFunction.cache[param] = result
    }
    return myFunction.cache[param];
}

console.log(myFunction("test"));
console.log(myFunction("test")); // do the same function call
console.log(myFunction("test 123")); // another call

console.log(JSON.stringify(myFunction.cache)); 
// {"test":{"result":"calculation for test"},"test 123":{"result":"calculation for test 123"}} 

Please note that this example only works with one parameter and only if it’s a primitive type (like a string).

Try the code here: http://jsfiddle.net/bfB9C/

If you want to learn more patterns like this one, check out JavaScript Patterns by O’Reilly.