Super-fast string handling in ColdFusion – Geekery
Ian Lurie Apr 29 2010
OK, getting VERY geeky here. You only want to read this post if:
- You program in ColdFusion. I’ve been using CF since the late 90s. It’s far and away my favorite programming language.
- You get happy tingly feelings when you make an application run 60-70% faster.
- You’re a nerd.
If you’re still here, this is a great tip for speeding up ColdFusion applications that handle really large strings:
Usually, in CF, you’d combine (concatenate) strings like this:
<CFSET string1 = “I”>
<CFSET string2 = ” am”>
<CFSET string3 = ” the nerdman!!! “>
<CFSET string1 = string1 & string2 & string3 & “mwahaha”>
Then this code:
would give you:
I am the nerdman!!! mwahahaha
But, if your strings get up to, say, 20,000 lines, this grinds to a halt. String concatenation can take 10 minutes instead of 10 seconds.
That’s ColdFusion’s way of telling you, “Enough already! Find a better way to put these variables together!”
And there is a better way.
The solution: Calling Java functions
ColdFusion is built on Java. So you can call some Java functions from within CF. Switch out the usual CFSET statements for a bit of Java code:
<cfset string1 = themap.concat(string1).concat(string2).concat(string3).concat(“mwahahaha”))>
concat is a Java string function. You can read about it until your eyes bleed here.
And the performance improvements will shock the hell out of you.
Real life example
I wrote an XML sitemap generator to go with Portent’s crawler. It worked brilliantly for 2000-3000 URLs. In about 10 seconds you’d have a nice, basic XML sitemap ready for deployment.
But we have some sites with hundreds of thousands of URLs. Any attempt to process a URL list that large using conventional ColdFusion failed. “Failed” is a bit of an understatement, actually. “Made our servers crank their fans up to maximum, caused lights across the globe to dim and nearly melted our server rack to slag” is a better description. The application would run and run, and even after 3-5 minutes, no result.
So, I used the concat function, plus CFSAVECONTENT.
The application now processes 120,000 URLs in under 10 seconds.
So this isn’t some tiny little performance tweak. This is a huge performance improvement that you can make with a couple of lines of code. ColdFusion geeks, rejoice!
Related and totally unrelated
CEO & Founder
Ian Lurie is CEO and founder of Portent Inc. He’s recorded training for Lynda.com, writes regularly for the Portent Blog and has been published on AllThingsD, Forbes.com and TechCrunch.
Ian speaks at conferences around the world, including SearchLove, MozCon, SIC and ad:Tech. Follow him on Twitter at portentint. He also just published a book about strategy for services businesses: One Trick Ponies Get Shot, available on Kindle.