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:

63 comments

  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. :’` I am very thankful to this topic because it really gives useful information “`-

  7. Tub Chair says:

    `:; I am very thankful to this topic because it really gives great information -.*

  8. Thanks for ones marvelous posting at http://odhyan.com/blog/2010/09/caching-in-javascript-yui-cache/! I truly enjoyed reading it, you could be a great author.I will be sure to bookmark your blog and will come back someday. I want to encourage you to continue your great job, have a nice weekend!

  9. Bud says:

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

  10. Greetings from Carolina! I’m bored to tears at work so I decided to check out your site on my iphone during lunch break. I love the information you present here and can’t wait to take a look when I get home. I’m shocked at how fast your blog loaded on my mobile .. I’m not even using WIFI, just 3G .. Anyhow, excellent site!

  11. I think this is one of the most vital info for me. And i am glad reading your article. But want to remark on some general things, The web site style is wonderful, the articles is really excellent : D. Good job, cheers

  12. weathervane says:

    Howdy! This is kind of off topic but I need some advice from an established blog. Is it difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about creating my own but I’m not sure where to begin. Do you have any points or suggestions? Many thanks

  13. Aw, this was a really nice post. In thought I want to put in writing like this moreover – taking time and actual effort to make a very good article… however what can I say… I procrastinate alot and by no means appear to get one thing done.

  14. 19. Great beat ! I wish to apprentice while you amend your site, how can i subscribe for a blog web site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear concept

  15. chicken coop says:

    Hey there! This is kind of off topic but I need some advice from an established blog. Is it difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about setting up my own but I’m not sure where to start. Do you have any tips or suggestions? Thanks

  16. BG mail says:

    I truly appreciate this post. I’ve been looking everywhere for this! Thank goodness I found it on Bing. You’ve made my day! Thank you again!

  17. I just wanted to construct a simple note to be able to say thanks to you for all of the marvelous solutions you are placing on this site. My incredibly long internet research has now been honored with sensible facts to write about with my friends. I ‘d point out that we site visitors actually are truly endowed to live in a really good network with very many brilliant individuals with beneficial pointers. I feel very lucky to have seen the web site and look forward to tons of more brilliant moments reading here. Thank you once again for a lot of things.

  18. yeah says:

    Attractive component to content. I simply stumbled upon your site and in accession capital to assert that I get in fact loved account your blog posts. Anyway I’ll be subscribing in your feeds or even I achievement you access persistently rapidly.

  19. Good site! I really love how it is simple on my eyes and the data are well written. I am wondering how I could be notified when a new post has been made. I’ve subscribed to your feed which must do the trick! Have a great day!

  20. Find Work says:

    I’ve been surfing online greater than three hours these days, but I never found any interesting article like yours. It is lovely worth enough for me. In my opinion, if all site owners and bloggers made excellent content material as you probably did, the internet will likely be a lot more useful than ever before.

  21. MovieReview says:

    I was just searching for this info for a while. After six hours of continuous Googleing, at last I got it in your website. I wonder what’s the lack of Google strategy that don’t rank this kind of informative sites in top of the list. Generally the top websites are full of garbage.

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

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

  24. I’ve recently started a blog, the information you offer on this site has helped me greatly. Thank you for all of your time & work.

  25. upominki says:

    Hey there, You’ve done an excellent job. I’ll certainly digg it and personally suggest to my friends. I’m confident they will be benefited from this web site.

  26. software says:

    Thanks for the sensible critique. Me and my neighbor were just preparing to do a little research on this. We got a grab a book from our local library but I think I learned more from this post. I’m very glad to see such fantastic information being shared freely out there.

  27. Again big article cheers heaps for sharing, keep me posted I’ll be reading much of your pieces in the next!

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

  29. vision51 says:

    Thanks for any other excellent article. The place else may anyone get that kind of info in such a perfect approach of writing? I’ve a presentation subsequent week, and I am on the look for such info.

  30. Hi, I am wondering have you got any kind of guest post oppertunitys available at all? I’d like to help with your site if I can, please answer right here and let me know!

  31. Thanks for sharing superb informations. Your web-site is very cool. I’m impressed by the details that you have on this blog. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my friend, ROCK! I found just the info I already searched everywhere and simply couldn’t come across. What a perfect web site.

  32. Please let me know if you’re looking for a article writer for your blog. You have some really great articles and I think I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for a link back to mine. Please send me an email if interested. Many thanks!

  33. excellent stuff :P really enjoyed this post, i’m going to read more in your blog after i’m finished with my work! ;)

  34. petunias says:

    You made some decent factors there. I regarded on the internet for the issue and found most people will go along with along with your website.

  35. An fascinating discussion is value comment. I believe that it’s best to write more on this matter, it won’t be a taboo topic however generally individuals are not enough to speak on such topics. To the next. Cheers

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

  37. Spot on with this write-up, I actually suppose this web site wants rather more consideration. I’ll probably be once more to learn far more, thanks for that info.

  38. I have read several good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative web site.

  39. Barby says:

    I just aspire to tell you that I am extremely new to running a blog and honestly savored you might be internet site. Probably I’m very likely to bookmark your site . You definitely have marvelous reports. Thank you a bunch for sharing with us your webpage.

  40. Hello there, simply was alert to your weblog thru Google, and found that it’s truly informative. I’m gonna be careful for brussels. I’ll be grateful if you happen to proceed this in future. A lot of folks will be benefited from your writing. Cheers!

  41. gambling bettingbonuses.biz

  42. Tegan Adams says:

    Oh my goodness! an amazing article dude. Thank you However I am experiencing difficulty with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting similar rss drawback? Anyone who knows kindly respond. Thnkx

  43. Mikel says:

    Your blog site is extremely beneficial. Thanks so much for delivering many advantageous subject matter. I’ve bookmark your blog webpage and can be without having doubt coming back. After yet again, I appreciate all your function as well as comeing below to talk with me.

  44. I just couldn’t depart your web site prior to suggesting that I actually loved the standard information an individual supply on your visitors? Is going to be again frequently in order to check out new posts

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

  46. It’s a shame you don’t have a donate button! I’d without a doubt donate to this brilliant blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this blog with my Facebook group. Talk soon!

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

  48. I am really loving the theme/design of your site. Do you ever run into any web browser compatibility problems? A few of my blog readers have complained about my website not operating correctly in Explorer but looks great in Firefox. Do you have any suggestions to help fix this problem?

  49. Keep up the wonderful piece of work, I read few posts on this website and I think that your web site is real interesting and has got sets of good information.

  50. Joe Boike says:

    I do assume your trusty audience may probably want a great deal more nicely written content articles this way carry on the amazing hard work. Love letters for him

  51. viagra says:

    Levitra…

    Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon….

  52. Ike Chicoine says:

    Attractive section of content. I just stumbled upon your website and in accession capital to assert that I acquire actually enjoyed account your blog posts. Any way I’ll be subscribing to your augment and even I achievement you access consistently fast.

  53. Amazing video, actually a fastidious quality, this YouTube video touched me a lot in terms of quality.

  54. more info says:

    Constantly, them will happen on one of the most inopportune situations in your current lowest requirement. In that period, problem occurs, whatever you could possibly perform, because the idea is without doubt in no way achievable to get some fresh home every single instance the application pauses.

  55. Deciding on well-insulated gates might tremendously better this energy source performance of families utilizing hooked up don, selling added pay-off.

  56. gold coins says:

    Thank you a lot for sharing this with all of us you really know what you are talking approximately! Bookmarked. Kindly also seek advice from my site =). We can have a link exchange contract between us!

  57. click here says:

    This allows us all watchfully night time when we have to utilize the cherished cars and trucks, in the particular receptive owed that will busted garage area doorstep. Current a long time, yard home fix offerings possess appeared while a new messiah to be able to spend less people as a result of most of concerns in connection with garage area déverrouillage.

  58. Getting a good moderately low-priced dwelling progress who uses lower than a fabulous morning to achieve, enhanced car port panels provide you with the prompt rise towards the landscaping with a fabulous property or home primarily as soon as the garage area panels confront a block.

  59. They may be designed using a real choice of resources, though just about the most well-known techniques is the particular timber-framed number mainly because these are excellent and so are moreover heavy duty.

  60. We’ve you should get some web web site to my stumbleupon accounts.and i also emailed this one post of yours to a several pals involving mine.

  61. thomas datt says:

    thomas datt…

    [...]c I must show some appreciation to you for bailing me out of this particular ny[...]…

  62. besok lubeck says:

    besok lubeck…

    [...]1 A cool post, I think blog owners should larn a lot from this site its ratt m3[...]…

  63. Great blog right here! Also your site lots up very fast! What host are you the usage of? Can I am getting your associate hyperlink in your host? I wish my web site loaded up as quickly as yours lol strona główna

Post a comment

Copyright © Saurabh Odhyan's Blog

Built on Notes Blog Core
Powered by WordPress