Server-side content caching in classic ASP

To minimize load on a backend SQL server and/or to ensure snappy performance on a website serving dynamic content, caching whole pages or parts of pages is often required.

This document gives a quick example on how to manage server-side content caching in the application object in classic ASP. Note that if you are building your pages in ASP.NET, there is a build-in caching system in the framework. However in classic ASP, you have to do it yourself, and this is one way of implementing a cache system.

The implementation is heavily inspired by 4 Guys From Rolla's A Real-World Example of Caching Data in the Application Object article.


<script language="vbscript" runat="server">

Sub Application_OnStart
  Application("UseCaching") = True
  Application("X_CacheAge") = 15  ' minutes
  Application("X_DateCached") = DateAdd("d", -1, Now())
End Sub

Sub Application_OnEnd
  ' Your application shutdown stuff here
End Sub

Sub Session_OnStart
  ' Your session start stuff here
End Sub

Sub Session_OnEnd
  ' Your session end stuff here
End Sub


Use the following code in the page needing cached content. The final content (coming from either the cache or the database depending on the cache age) will be stored in the strContent variable. The GetContentFromDB() function should return the content needing caching. Note that the application object is not limited to storing text strings. An array can for example be used to store multiple elements needed to generate the final page.

Dim strContent
If Application("UseCaching") = True Then
  If (DateDiff("n", Application("X_DateCached"), Now()) > Application("X_CacheAge")) Or (IsEmpty(Application("cache_X"))) Then
    strContent = GetContentFromDB()
    Application("cache_X") = strContent
    Application("X_DateCached") = Now()
    strContent = Application("cache_X")
  End If
  strContent = GetContentFromDB()
End If

Note that the cache entry is named "cache_X". By using this naming convention (prefixing different cache elements with "cache_"), a central cache-clearing function can be implemented:

Sub ClearCache()
  Dim objAppKey
  For Each objAppKey in Application.Contents
    If Left(objAppKey, 6) = "cache_" Then
      Application(objAppKey) = Empty
    End If
End Sub
Tags: asp
Page last updated 2007-07-15 17:50. Some rights reserved (CC by 3.0)



RSS 2.0 feed All content
RSS 2.0 feed ajax
RSS 2.0 feed asp
RSS 2.0 feed aspnet
RSS 2.0 feed bicycle
RSS 2.0 feed copenhagen
RSS 2.0 feed databases
RSS 2.0 feed denmark
RSS 2.0 feed diy
RSS 2.0 feed dotnet
RSS 2.0 feed html
RSS 2.0 feed japan
RSS 2.0 feed javascript
RSS 2.0 feed modding
RSS 2.0 feed photography
RSS 2.0 feed utilities
RSS 2.0 feed vbscript