How Caching Means More Ca-ching, Part 2 - Methods
(Page 2 of 4 )
Method # 1: the Cache Method
This is by far the simplest way to get your object/data into the cache. If you're at all familiar with classic ASP, you'll see it's as easy as using session variables. If you're new to all of this, then you're about to see just how easy it really is. Here's the incredibly large amount of code you will need to type in order to store an item in the cache:
strVal
= "something trivial"
cache("item") = strVal
So that's it. 'item' is the variable name you will use, and 'value' is none other than -- you guessed it -- the value! But how do we now retrieve the item once it's sitting in memory? Also, not very difficult:
newVariable
= cache("item")
There, wasn't that far less painful than a trip to the dentist? But you may be wondering if we're limited to storing simplistic variable such as the string I used in the example. Well, recall that this is caching at the object level. So any object, for instance an array, can certainly be stored this way! Now I sense you are starting to get excited, beginning to understand the power and versatility of data caching.
But if you really examine this first method, you'll agree that it's very basic. All you can do it add and retrieve items from the cache. There's really no further level of control granted us. For instance, how do we tell the application when to oust the object from memory at a given time to free up resources? We don't; It just remains there until a server restart or explicit removal (through the cache.remove(“item”) method), which is far too onerous of a task for most developers to bother with. Hmm, you're thinking that something more is needed. Well, something more is given, let's check it out!
Methods #2 & #3, .Insert & .Add
Now we move beyond the restrictions of the Cache method. We take the control of the cache-flow out of the hands of the server, and place it where it should be, in your hands. You and I will get to determine the lifetime of the objects, either with time expiration, external dependencies, or even based on priority against other cached objects. Before we do that though, I'll just quickly show you how to use these methods in their raw form, wit no options:
strVal
= "this is SOOO exciting!"
cache.insert("item", strVal)
'or
cache.add("item", strVal)
Why you would choose one method over the other will not be readily apparent yet. Really the only difference is that cache.add has one extra option, that of returning an object representing the cached data. Other than that option, the syntax for both is the same, so I'll only use one method in my example, and you can interchange as you see fit. So why don't we just proceed through these one at a time, starting with the expiration option.
Next: You're Too Old, Please Leave >>
More ASP.NET Articles
More By Justin Cook