Groovy performance for file IO

As part of the work I’m doing trying to automate a migration from Struts to Spring MVC, I’ve been writing a Groovy script to process the struts config file. I need to add a couple of lines to the file. Unfortunately, editing a file in this way is something that is always rather fiddly to do. What you usually end up doing is reading the file line by line, writing each line to a second file, adding or removing lines where you need to. Then you delete the old file and rename the second one. However, Groovy has good support for both file IO and regular expressions, so you can easily write something like the following :
oldStrutsFile.eachLine{ line ->
	// copy the line in
	newStrutsConfig.append(line + "n")
	// add controller
	if (line =~ /</action-mappings/) {
		newStrutsConfig.append('spring controller info here')
	}
	// plug in
	if (line =~ /END MERGED RESOURCES/) {
		newStrutsConfig.append('spring plug-in info here')
	}	
}
However, when I ran the Groovy script I was amazed at how slow it was. It took approximately a minute to update the struts file. It is a reasonable size (177k) but even so the time is excessive. For comparison, I then rewrote this part of the code using Java. (I still kept it embedded within the Groovy script though):
FileReader reader = new FileReader(oldStrutsFile)
FileWriter writer = new FileWriter(newStrutsConfig)
String line = null;
while ( (line = reader.readLine()) != null) {
	// copy the line in
	writer.write(line + "n")
	// controller
	if (line =~ /</action-mappings/) {
		// write the extra lines
		writer.write('spring controller info here')
	}
	// plug in
	if (line =~ /END MERGED RESOURCES/) {
		writer.write('spring plug-in info here')
	}
}
This took 141 milliseconds to run, a phenomenal difference. For me, the lesson here is that if you are an experienced Java programmer, and you want to use Groovy, don’t feel that you have to use Groovy syntax all time, just because it is there. One of the great things about knowing more than one programming language is that you can choose the best tool for any particular job. With Groovy this is particularly true, as you can embed regular Java within Groovy whenever you like, to get the best of both languages.
This entry was posted in Groovy and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

HTML tags are not allowed.

518,181 Spambots Blocked by Simple Comments