Experimenting With Flat-File ColdFusion CFML Caching

<!---
	Prepare the cache. One cache will be using a struct-based
	cache and the other will be using a file-based cache that
	writes out ColdFusion code.
--->
<cfset objCache = {} />
 
<!--- Get the cache directory. --->
<cfset strCacheDirectory = ExpandPath( "./cache/" ) />
 
 
<!--- Set the cache test size. --->
<cfset intCacheSize = 10000 />
 
 
<!--- Loop over a large set to create a large cache. --->
<cfloop
	index="intIndex"
	from="1"
	to="#intCacheSize#"
	step="1">
 
	<!--- Create an in-memory cached item. --->
	<cfset objCacheItem = {
		Index = intIndex,
		Message = "This is cached item: #intIndex#",
		DateCreated = Now()
		} />
 
	<!--- Add the item to the cache struct. --->
	<cfset objCache[ intIndex ] = objCacheItem />
 
	<!---
		Check to see if we are building the flat file cache. We
		do NOT want to do this every run of the page because that
		will cause ColdFusion to re-compile the templates each
		time which had a LARGE up-front load. In reality, these
		would be written to file and then called many times,
		allowing ColdFusion to compile them efficiently.
	--->
	<cfif StructKeyExists( URL, "publish" )>
 
		<!---
			Create the ColdFusion code for this item. When doing
			this, we have to escape the openning CF tags so they
			don't get evaluated. We also have to evaluate all the
			variables so they can be written out.
		--->
		<cfsavecontent variable="strCFCode">
 
			<[cfset $cache = {
				Index = #intIndex#,
				Message = "This is cached item: #intIndex#",
				DateCreated = "#Now()#"
				} />
 
		</cfsavecontent>
 
		<!--- Write ColdFusion code to flat file. --->
		<cffile
			action="write"
			file="#strCacheDirectory##intIndex#.cfm"
			output="#Trim( Replace( strCFCode, '<[', '<', 'all' ) )#"
			/>
 
	</cfif>
 
</cfloop>
 
 
<!---
	If we just published the flat-file templates, don't bother
	running the test (the combination of CFFile writing and then
	compiling the templates will run the page out of time). Let's
	just publish once and then run separately.
--->
<cfif StructKeyExists( URL, "publish" )>
 
	<cfabort />
 
</cfif>
 
 
<!---
	Now that we have our cache in place, let's loop over each to
	see how fast they each respond. The Flat-file system will be
	slower, but how much?
--->
<cftimer type="outline" label="In-Memory Cache">
 
	<cfloop
		index="intIndex"
		from="1"
		to="#intCacheSize#"
		step="1">
 
		<!--- Get cached item. --->
		<cfset $cache = objCache[ intIndex ] />
 
	</cfloop>
 
	Done.
 
</cftimer>
 
<br />
 
<!---
	Now, let's do this again, but with the flat file. We
	have to do a CFInclude tag to get the cached data back
	into memory.
--->
<cftimer type="outline" label="Flat-File Cache">
 
	<cfloop
		index="intIndex"
		from="1"
		to="#intCacheSize#"
		step="1">
 
		<!--- Get cached item. --->
		<cfinclude template="./cache/#intIndex#.cfm" />
 
	</cfloop>
 
	Done.
 
</cftimer>

For Cut-and-Paste