Recently I set up a brand new client to eat some API dogfood I created for one of my upcoming projects. While creating this app I came across some interesting problems I try to solve in a different way every time I face them.
How to intelligently cache collection objects in a Backbone.js based application?
Well, most people will answer now: “Why not memoize the collection, or at least the object (view) that contains it’s reference?” I’d answer, that this works in most simple applications, but the more complex it gets, the more likely it is, this approach will kill you.
After spiking around a little I came up with the following (in my opinion very neat) solution:
To make use of this CollectionCache I do the following, every time I instantiate a collection or reference one that should exist already (in the cache).
Global() in that case is a singleton that allows me to get rid of namespaces and really global objects. Everywhere I need it, I pass it in, and it gives me a reference to my cache object.
This one can be called with the reference of a constructor (in my case FoosCollection)as well as every number of instantiation arguments. In case the cache already has an object that matches this instantiation signature, it returns this guy. In case not, it creates a new one making use of all the arguments, passed in together with the constructor reference.
As a result, the collection is created exactly once in the whole lifecycle of the application. Every object that needs it, gets exactly the same reference. Last but not least, you have to decide, whether to fetch the collection during runtime or not.
The code is straight forward as I think. The only external requirement is a MD5 implementation of your choice. Quite sure, MD5 brings in some complexity, as well as slows down everything. So here’s some space for optimization.
Obviously this cache object can be utilized not only to cache collections but every kind of object. It’s reliability comes out of the mechanism to create the keys. I am curious for better solutions.
Recently, I have noticed (once again) that the last update my own website has been a while ago. 5 years to be exact. For someone who earns a large portion of his income with the creation of modern web applications, it should at least not be the standard. (Even if most of us know, that full time jobs plus side projects plus family and friends usually do not allow things like that.)
Therefore, an update was more than necessary.
Anyway, I assume that investing my time in interesting projects in the future may be more important than keeping a private blog. Nevertheless, I will try and publish from at least a few things that I find interesting.