Please note, new blog at http://www.acheron.org/darryl/

Using Arrays for String Concatenation

In response to my previous post about using Java for String concatenation instead of ColdFusion’s concatenation operator, Greg has given me an interesting tip. It turns out that ArrayAppend() is a LOT quicker than regular concatenation, and the StringBuffer class! If you’re generating a CSV string, all you have to do is put each line into an array element using the ArrayAppend() method. Once all lines have been appended, convert the array to a list using the ArrayToList() method, using #chr(13)##chr(10)# as the delimiter. I decided to run the same sorts of tests that I have before. This time, I compared concatenating a string with regular string concatenation, the ArrayAppend method and the Java StringBuffer class. Using ArrayAppend was certainly the quicker of the three – by a long way. So, if you’re building a small-medium length string, then ArrayAppend is the way to go. However, a word of caution. If you are creating a large CSV file, then use the Java methods I have discussed before.

Results

Code Examples

Regular string concatenation <cftimer type="inline" label="Regular concentation"> <cfscript> iNrTimesToLoop = url.nr; sStringToConcat = "The quick brown fox jumped over the fence: "; sString = ""; for (x=1; x LTE iNrTimesToLoop; x=x+1) { sString = sString & sStringToConcat & x; } </cfscript> </cftimer> ArrayAppend <cftimer type="inline" label="ArrayAppend"> <cfscript> iNrTimesToLoop = url.nr; sStringToConcat = "The quick brown fox jumped over the fence: "; aString = ArrayNew(1); for (x=1; x LTE iNrTimesToLoop; x=x+1) { temp = ArrayAppend(aString, sStringToConcat & x); } // Convert back into a string sString = ArrayToList(aString, "#chr(13)##chr(10)#"); </cfscript> </cftimer>

By Anonymous Anonymous, at 10/03/2005 03:24:00 am  

I put together a similar test for Flash.. diferent results entirely of course..

http://oddhammer.com/actionscriptperformance/set3/index.html
(test #15)



By Anonymous Anonymous, at 10/06/2005 03:57:00 am  

<cftimer type="inline" label="ListAppend">
<cfscript>
iNrTimesToLoop = url.nr;
sStringToConcat = "The quick brown fox jumped over the fence: ";
aString = "";

for (x=1; x LTE iNrTimesToLoop; x=x+1)
{
temp = ListAppend(aString, sStringToConcat & x);
}

</cfscript>
</cftimer>


We achieve better times as we avoided using 2 function calls
- ArrayNew(1)
- ArraytoList()



By Anonymous Anonymous, at 10/06/2005 04:03:00 am  

try url.nr > 20000 to see some appreciable diff between the 2 methods



» Post a Comment