Pages

Tuesday, July 3, 2012


Memoization

Once an expensive function runs, it can rewrite itself with an optimized version.

Memoization is a technique similar to caching that takes advantage of
the fact that functions are just data.

var getElement = function() {

    console.log("creating element");
    var element = document.createElement("div");

    // ... Do a bunch of expensive operations

    // Now OVERWRITE this function with a SIMPLER VERSION
    getElement = function() {
        return element;
    };

    return element;
};

The first time getElement runs, it creates the element and runs a bunch
of code with it. Then it rewrites the getElement function to solely return the created element. This makes subsequent calls to getElement much quicker.



No comments:

Post a Comment