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:

15 thoughts on “Caching in Javascript (YUI Cache)

  1. [...] This post was mentioned on Twitter by YUI Library, Andrew Wooldridge, Tifosi, Philip Tellis, Luke Smith and others. Luke Smith said: RT @bluesmoon: caching in javascript with YUI3: http://odhyan.com/blog/2010/09/caching-in-javascript-yui-cache/ #yui [...]

  2. [...] ever needing to look at the docs.” Check out the full article for more. (Original source.) #Saurabh Odhyan on the YUI 3 Cache Utility: Writes Saurabh: YUI 3 Cache “allows to cache frequently used data in javascript memory [...]

  3. Jagan says:

    Hi,

    this.memo[key] = val; what is the maximum val size ? can i store 250 MB data?

  4. Saurabh says:

    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.

  5. roclafamilia says:

    Helpful blog, bookmarked the website with hopes to read more!

  6. Bud says:

    excellent site. many thanks for this excellent write-up. i love lots.

  7. elgoog says:

    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.

  8. 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!

  9. 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.

  10. Thanks for the post.It was really useful to resolve my confusion

  11. website zone says:

    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.

  12. It’s the best time to make some plans for the future and it is time to be happy. I have read this post and if I could I desire to suggest you few interesting things or advice. Maybe you can write next articles referring to this article. I desire to read even more things about it!

  13. "article" says:

    “article”…

    “[...]7 I was rattling happy to find this site on bing, just what I was searching f mv[...]“…

  14. “a total noob”…

    “[...]l All the cool facts about News means very much to us. 0m[...]“…

  15. Happy says:

    Thanks , I’ve recently been looking for info about this topic for a long time and yours is the best I’ve came upon so far. But, what about the bottom line? Are you positive concerning the supply?

Comments are closed.