Simon Baynes: Web Development

Using Java to Optimise Looping Over Lists

Once you have been using ColdFusion for a while you will have undoubtedly had to loop through a list. Now this is very straight forward operation and one where you rarely have to consider performance. However, if you are reading in a 10,000+ row CSV file this iterative process can be very slow. Many of you would do something like this:-

<cfloop list="#myCSV#" index="thisRow">
    <!--- here is where you would do your row processing --->
</cfloop>

Now there is essentially nothing wrong with this code, however this processing is not optimal performance-wise. Fortunately you can access the power of the underlying Java to up the performance.

<!--- here we use the java.lang.String class to convert our CSV into an array using the split() method --->
<cfset myCSV = createObject("java", "java.lang.String").init(myCSV).split(chr(13) & chr(10))>

<cfloop from="1" to="#arrayLen(myCSV)#" index="thisRow">
    <!--- here is where you would do your row processing --->
</cfloop>

I have seen this provide enormous performance gains.

By Simon Baynes