Caching in Javascript (YUI Cache)

Today I read about YUI 3 Caching Utility. It allows to cache frequently used data in javascript memory (Basic caching) or HTML5 localStorage object (Offline caching). Although we can implement our own caching mechanism in javascript, the YUI caching is general purpose and also provides a set of events. Moreover it can be easily integrated with YUI Datasource which can be very beneficial.

I’ll show you how useful YUI caching utility can be using a very standard example, Factorial. Here I’ll only cover basic caching.

Let’s write a factorial program in javascript without any caching/memoization:

YUI().use('node', function() {
    // method to calculate factorial
    var factorial = function(n) {
        if(n === 0 || n === 1) {
            return 1;
        } else {
            return n * factorial(n-1);
        }
    }
    // calulate the factorials and display the values on browser
    var MAX = 100,
        ret = "",
        el,
        i;
    for(i = 1; i < MAX; i++) {
        ret += i + "! = " + factorial(i) + "</br>";
    }
    el = document.getElementById("fact"); // create this div in HTML code
    el.innerHTML = ret;
});

Try increasing the value of MAX and you’ll see that your browser may get very slow/crash. My firefox keeps on running the script and then shows a dialog box to stop the script. I assume all must be familiar with factorial and should be able to understand why this program is highly inefficient.

Now lets write another factorial program using our own caching mechanism:

YUI().use('node', function() {
    // create a cache class
    var MyCache = function() {
        this.memo = [];
    };
    MyCache.prototype.add = function(key, val) {
        this.memo[key] = val;
    };
    MyCache.prototype.retrieve = function(key) {
        return this.memo[key];
    };
    // a new cache object
    var cache = new MyCache();
    // method to calculate factorial
    var factorial = function(n) {
        var ret;
        if(n === 0 || n === 1) {
            return 1;
        } 
        ret = cache.retrieve(n);
        if(ret !== undefined) {
            return ret;
        } else {
            ret = n * factorial(n-1);
            cache.add(n, ret);
            return ret;
        }
    };
    // calulate the factorials and display the values on browser
    var MAX = 100,
        ret = "",
        el,
        i;
    for(i = 1; i < MAX; i++) {
        ret += i + "! = " + factorial(i) + "</br>";
    }
    el = document.getElementById("fact"); // create this div in HTML code
    el.innerHTML = ret;
});

The above code runs smoothly even if we increase the value of MAX(even 5000 should be fine although 5000! doesn’t make sense). That’s because we cache the value of every factorial we calculate and then reuse it for the next calculation.

Now lets write the same program using YUI caching utility:

YUI().use('cache', function(Y) {
    // create a yui cache object
    var cache = new Y.Cache({
        max:100
    });
    // method to calculate factorial
    var factorial = function(n) {
        var ret;
        if(n === 0 || n === 1) {
            return 1;
        }
        ret = cache.retrieve(n);
        if(ret !== null) {
            return ret.response;
        } else {
            ret = n * factorial(n-1);
            cache.add(n, ret);
            return ret;
        }
    }
    // calulate the factorials and display the values on browser
    var MAX = 100,
        ret = "",
        el,
        i;
    for(i = 1; i < MAX; i++) {
        ret += i + "! = " + factorial(i) + "</br>";
    }
    el = document.getElementById("fact"); // create this div in HTML code
    el.innerHTML = ret;
});

This also runs smoothly for large values of MAX.

For this particular example, implementation 2 (using our own caching) will be slightly more efficient than the YUI version due to the simplicity, but in more complex examples, YUI caching utility can be quite useful.

You can read more about the YUI Cache here.

Related links:

16 Comments on "Caching in Javascript (YUI Cache)"




  1. Jagan,
    There is no limit as such. You can store as much data as you wish until the system runs out of memory. But huge amount of data will obviously hurt performance.

    Reply

  2. I just couldn’t depart your web site before suggesting that I actually loved the usual info an individual supply in your guests? Is going to be back incessantly to check up on new posts.

    Reply

  3. Good web site! I truly love how it is simple on my eyes and the data are well written. I’m wondering how I could be notified whenever a new post has been made. I have subscribed to your feed which must do the trick! Have a great day!

    Reply

  4. I have to voice my appreciation for your kindness supporting those who must have guidance on that content. Your real dedication to getting the solution all through has been surprisingly powerful and have constantly helped associates like me to attain their pursuits. Your personal useful key points denotes a great deal a person like me and a whole lot more to my colleagues. Regards; from all of us.

    Reply

  5. Nearly all of whatever you say is supprisingly legitimate and that makes me wonder the reason why I had not looked at this in this light before. This particular article truly did switch the light on for me personally as far as this specific subject matter goes. Nevertheless at this time there is one point I am not necessarily too comfortable with and while I try to reconcile that with the main theme of your position, permit me observe exactly what the rest of the readers have to say.Very well done.

    Reply



  6. An outstanding share! I’ve just forwarded this onto
    a co-worker who has been conducting a little homework on this.
    And he actually bought me dinner simply because I discovered it for him…
    lol. So let me reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending the time to discuss this matter here on your website.

    Reply

  7. Wonderful beat ! I wish to apprentice at the same time as you amend your web site, how could
    i subscribe for a weblog website? The account aided me a acceptable deal.
    I have been a little bit familiar of this your broadcast offered vibrant transparent idea

    Reply

Leave a Reply

Your email address will not be published.