Friday, June 20, 2008

Caching Data in ASP

Do you have a web page that takes a long time to generate? Do you have a SQL query that you want to cache the results? This tutorial will show how to use Application variables to store cached data.

Application Variables
The Application object allows you to store data in a single location that can be shared by one or more ASP files in a directory and its subdirectories. The Application object stores data by a named index. You can store any type of data in the Application object including strings, dates, and numbers. To cache data, we will store multiple kinds of data in the Application object.

Below are some examples of storing data in the Application object:


<%
Application("string")="hello world"
Application("time")=now()
Application("number")=86
%>

The Application object values can be accessed the same as any other ASP variables / objects. The following example shows how to display the value of the an Application value:


<%=Application("string")%>

Threading
Since the Application object is available to all pages, it can be accessed by multiple threads / users at once. To prevent multiple threads / users from updating the shared object at the same time, you will need to call the Lock and Unlock methods. The following example shows how to lock and unlock the Application object before setting a value:


<%
Application.Lock
Application("cache")="hello world"
Application.Unlock
%>

Time Stamping the Cache
Now that data is stored in the cache, you will want to set a time interval that the cached data is valid. To do so, a cache time will also be stored in the Application object. The following example shows how to set the cache time stamp:


<%
Application.Lock
Application("cache")="hello world"
Application("cache-timestamp")=now()
Application.Unlock
%>

Next, the current time will need to be compared against the cache time stamp to see if the cache needs to be updated. For the example below, the cache will be updated every 12 hours. The datadiff function is used to compare the current time against the cache time stamp.


<%
if datediff("h", Application("cache-timestamp"), now()) >= 12 then
Application.Lock
Application("cache")="hello world"
Application("cache-timestamp")=now()
Application.Unlock
end if

Response.Write("cache")
%>

Summary
The Application object is an easy way to cache data within an application. This is an easy way to improve the performance of a dynamically generated web page. Some situations that you may want to use this mechanism is for slow SQL queries, dynamic HTML, RSS feed results, and web services results.

Reference
  • Application Object - Information on the Application object from the Microsoft documentation.
  • Date Arithmetic - Learn how to perform date arithmetic with the datediff function.
  • datediff - Information on how to use the datediff function.

0 comments: