HJCotton.net

December 12, 2009

CF9 Ternary Operator

by @ 11:22 pm. Filed under Coldfusion.

Coldfusion 9 finally has a ternary operator. It’s certainly a lot prettier to use than an IIF(), and you won’t have to deal with those odd occasions where you need to use DE() to get things to work. Here’s an example of how it works in CF9 and the equivalent using an IIF() and a standard “if” (keep in mind that the loops are to demonstrate performance only – they are otherwise quite out-of-place):

<cfparam name="URL.name">
<cfparam name="URL.isLight">
 
<cfset startTernary = GetTickCount()>
<cfloop from="1" to="10000" index="i">
	<cfset beerName = !URL.isLight? URL.name & " is a good beer" : "No light beers in this list!">
</cfloop>
<cfset endTernary = GetTickCount()>
 
<cfset startIIF = GetTickCount()>
<cfloop from="1" to="10000" index="i">
	<cfset beerName = IIF(!URL.isLight, "'#URL.name# is a good beer'", "'No light beers in this list!'")>
</cfloop>
<cfset endIIF = GetTickCount()>
 
<cfset startIf = GetTickCount()>
<cfloop from="1" to="10000" index="i">
	<cfif URL.isLight>
		<cfset beerName = "No light beers in this list!">
	<cfelse>
		<cfset beerName = "#URL.name# is a good beer">
	</cfif>
</cfloop>
<cfset endIf = GetTickCount()>
 
<cfoutput>
	Ternary: #endTernary - startTernary#ms<br />
	IIF: #endIIF - startIIF#ms<br />
	If: #endIf - startIf#ms<br />
</cfoutput>

Even over 10,000 iterations, the ternary option is head-to-head with a standard if statement, and only slightly faster than an IIF:
Ternary: 62ms
IIF: 77ms
If: 62ms

I’ve always heard that IIFs were slow, but I’ve always found them so handy that I overlooked whatever the performance consequences might be. While noticeable in these tests, it’s not something that would affect most projects at all. These results are also backed up in this post by Ben Nadel.

I won’t be using CF9 in a production setting in the immediate future, so until then it’ll still be IIFs for me. Still, some of these new language improvements and features are definitely worth looking into (even if they should have been added long ago!).

Leave a Reply

HJCotton.net

pages:

categories:

search:

archives:

September 2010
S M T W T F S
« Aug    
 1234
567891011
12131415161718
19202122232425
2627282930  

So it goes.
— Kurt Vonnegut

general links:

3shot.jpg

3shot.jpg

01-23-2010

01-23-2010

other:

Page 1 of 0

24 queries. 1.704 seconds