I’m investigating some basic, everyday operations that many web application developers face.  Using very simple test cases, I’m determining if there is a time savings by writing Java code and calling it from ColdFusion.  If there is a savings, is it worth the extra coding time and overhead* for using Java.  Here’s the result of my first, basic test.

File Read/Write Operations

I was actually surprised how much faster invoking a Java I/O class was than the equivalent code in ColdFusion.  Using only a 90k byte file, I wrote a Java class to read it, parse it on a delimiter of the pattern ‘x\s’ and output each line.

public String outputScannedFile() throws IOException
{
   Scanner s = null;
   String output = "";
   try {
       s = new Scanner(new BufferedReader(new FileReader("C:\\inputfile\\xanadu.txt")));
       s.useDelimiter("x\\s*");
       while (s.hasNext()) {
      	  output += s.next();
       }
   } finally {
       if (s != null) s.close();
   }
   return output;
}

This is executed by creating an instance of a class and invoking a method (I use cfscript for Java objects… easier to read)

<cfscript>
output = createobject("java", "orbwave.StringTest");
</cfscript>
<cfdump var="#output.outputScannedFile()#">

This executed at a good pace.

Execution Time

Total Time Avg Time Count Template
3078 ms 3078 ms 1 C:\jboss-4.0.4\server\default\.\deploy\brownlees.war\scribble.cfm

The equivalent code in ColdFusion is much easier to write

<cffile action="read" file="C:\\inputfile\\xanadu.txt" variable="input">
<cfloop from="1" to="#ListLen(input,'x')#" index="span">
	<cfoutput>#ListGetAt(input,span,'x')#</cfoutput>
</cfloop>

It also took over twice as long to execute.

Execution Time

Total Time Avg Time Count Template
7484 ms 7484 ms 1 C:\jboss-4.0.4\server\default\.\deploy\brownlees.war\scribble.cfm

As one would expect, using Java to handle the I/O is faster. However, I did not expect the compilation and execution of a simple set of ColdFusion commands to take over 4 seconds longer on such a basic operation.

Is It Worth It?

In situations where you’re performing a significant amount of file I/O, I would suggest writing some simple Java classes, compressing them to a JAR and installing it on your app server.

* By overhead, I’m not talking about system resource overhead, but the additional resources needed to maintain Java in addition to ColdFusion, such as source control measures, training (if necessary), compile-time and build-time.