Simple example of how to cache data

posted on 11 January 2008 | posted in Coding

You will want to cache parts of your website that are costly to CPU usage. For example, you might have an e-commerce website that lists its product categories down the left-hand side of every page. This list might be generated from the database every time a page is loaded on the site. Think about all those daily visitors multiplied by several page loads per visitor - it adds up. Imagine if that CPU usage was wiped out and instead static HTML was loaded in its place? This is known as caching - using static HTML instead of making a trip to the database.

The following is a simple example of how to cache data - we will use the example above : a simple list of categories. The example is to show the concept of caching and the scripting logic involved. You can of course extrapolate this logic to any language (PHP, .NET etc) - this example is in ASP.

Example code of caching a category list

Dim rs,strCachedHTML

'strCachedHTML is the string that will contain all of the cached HTML generated in this script

'Following is connection to database to retrieve list of product categories; use your own syntax to connect to your database - this is just an example
ExecuteQuery ("SELECT CatName FROM Categories ORDER BY CatName ASC;")

'Loop through categories
    strCachedHTML=strCachedHTML & "<li>" & rs.Fields ("CatName") & "</li>"
Set rs=Nothing
strCachedHTML=strCachedHTML & "</ul>"

'Delete cache file if it already exists
IF fso.FileExists (Server.MapPath ("cached/categories.asp")) THEN
    fso.DeleteFile(Server.MapPath ("cached/categories.asp"))

'Now create cache file and put the contents of the string strCachedHTML into it; use your own directory structure if you want
set myFile = fso.CreateTextFile(Server.MapPath ("cached/categories.asp"))
myFile.WriteLine (strCachedHTML)
Set fso=Nothing

How to call the cached file on your web page

In ASP, you can simply INCLUDE this static ASP page using the following:-

<!-- #include file= "cached/categories.asp" -->

When and where to cache

It's not essential (or often practical) to cache every single part of your website. You should target the common areas like dynamic navigation (such as a category list) or perhaps all areas of the front page of a website (likely the most visited page by far).

Remember when to update the cache!

In the above example, the cached file would need to be updated every time there's a change to the category list: when a category is added, deleted, or its name amended. You should create your script that caches as a class/procedure that can be called simply by name (e.g. GenerateCache).


Caching is actually quite an easy process to do, and the benefit is greatly reduced CPU usage (the major killer of servers is CPU overload).

recommend a friendRecommend this blog entry to a friend