Saturday, September 13, 2008

cfsavecontent vs. cfset for performance improvement

Many CF programmers out there know that coldfusion uses java string objects to store its variables usually. And since java strings are "immutable", every time you change it, a new string is created.
If you find yourself doing huge amounts of string concatenations, you'll often see people suggesting that you look up the java StringBuffer object and use that instead. That would allow you to append to a single StringBuffer object rather than creation a million string objects.
But there's another solution, apparently.
CFSAVECONTENT is so ridiculously fast compared to the old string concatenation method with CFSET that it has got to be using a StringBuffer behind the scenes. At least, that's what I'm thinking.
Take the following code, for example. On my local machine, the CFSET method took 64 seconds to complete. The CFSAVECONTENT method completed in a mere 203ms.
Also, the memory consumption of the CFSET method was significant, while the CFSAVECONTENT method was hardly noticeable.

<cfsetting enablecfoutputonly="yes">
<cfsetting requesttimeout="600">
<cfset reps = 100000>
<cfif 1>
<cfset start = now().gettime()>
<cfset result = "">
<cfloop from="1" to="#reps#" step="1" index="i">
<cfset result = result & i>
</cfloop>
<cfset end = now().gettime()>
<cfoutput><p>#end-start#ms : #len(result)#</p></cfoutput>
<cfelse>
<cfset start = now().gettime()>
<cfsavecontent variable="result">
<cfloop from="1" to="#reps#" step="1" index="i">
<cfoutput>#i#</cfoutput>
</cfloop>
</cfsavecontent>
<cfset end = now().gettime()>
<cfoutput><p>#end-start#ms : #len(result)#</p></cfoutput>
</cfif>

No comments: