Simple page caching in ASP

24 May 2007
Speed up page download with this simple content caching script. Makes use of Application variables to store content for a set time period. Store content returned from a function, be it a whole page or just a small portion.

'-----------------------------------------------------
'| Page Cache (c) Andrzej Marczewski 2007 V 1.00 |
'-----------------------------------------------------
'This is a really simple caching system. The idea is that you have a function that returns some page content.
'You want this content to be cached to save some server load, maybe because it hits a database a number of times.
'For example
'function news()
' newsbulider = "This is the news " &_
' "Headline 1" &_
' "Headline 2" &_
' news = newsbulider
'end function
'To cache this and have it display on the page you would use
'response.write(getCache("news","news_cache",60))
'The first part is the funciton you are calling, news.
'The second parameter is the name of the application variable that will be created, news_cache
'The final parameter is the length of time, in minutes, that the cache is kept for.
'In this case the cache will not be refreshed for 60 minutes.
'This will not only reproduce what is in the cache, ubt if the cache has not been created or is out of date it will fill the cache with content.
'You can also manually fill the cache manually. I use this once I have added news, so the cache is refreshed straight away, rather than waiting an hour!
'setCache "news","news_cache"

public function getCache(cacheFunc,cacheVar,cacheTimeout)
dim arr
arr = application(cacheVar)
if typename(arr) = "Variant()" then
if cacheTimeout > 0 AND (datediff("n",arr(1),now()) >= cacheTimeout OR arr(0)="") then
arr = setCache(cacheFunc,cacheVar)
end if
else
arr = setCache(cacheFunc,cacheVar)
end if
getCache = arr(0)
end function

function setCache(cacheFunc,cacheVar)
dim arr(1)
arr(0) = eval(cacheFunc)
arr(1) = now()
Application.Lock
application(cacheVar) = arr
Application.UnLock
setCache = arr
end function

 

blog comments powered by Disqus