Company Blog RSS Feed

ColdFusion CFSwitch vs. CFIF

September 14, 2011
The <cfif> and <cfswitch> tags are used to evaluate an expression you pass to it and find a match. First, lets look at how a <cfif> tag can be structured. In this example, we'll evaluate the variables.myVar variable and look for a value of 1, 2, 3, or anything else:

<cfset variables.myVar = 3>

<cfif variables.myVar eq 1>
    The value of "myVar" is 1
<cfelseif variables.myVar eq 2>
    The value of "myVar" is 2
<cfelseif variables.myVar eq 3>
    The value of "myVar" is 3
<cfelse>
The value of "myVar" is neither 1, 2, or 3
</cfif>


First, variables.myVar is set to 3, then we use <cfif> to evaluate the variable and output the necessary text to the screen. This works great and can be used if you wish, however, the code is not very clean and, if you wanted to add more value choices in your IF statement such as evaluating 4, 5, 6, etc., this code will be very dirty and hard to read. In this case, you can turn to the <cfswitch> tag to evaluate your expression. The equivalent of the above code using the <cfswitch> tag is:

<cfset variables.myVar = 3>

<cfswitch expression="#variables.myVar#">
    <cfcase value="1">
        The value of "myVar" is 1
    </cfcase>
    <cfcase value="2">
        The value of "myVar" is 2
    </cfcase>
    <cfcase value="3">
        The value of "myVar" is 3
    </cfcase>
    <cfdefaultcase>
        The value of "myVar" is neither 1, 2, or 3
    </cfdefaultcase>
</cfcswitch>


Running both examples will give you the same output. In short, <cfif> is a great tag to use if you are doing a simple if/else evaluation. It's clean, quick, and to the point. <cfswitch> is great to use if you are evaluating an expression that could have many outcomes, like the above example.

I did speed tests for both examples and received the same results. If anyone would like to chime in regarding speed differences between the two examples, feel free to.

Happy coding!



Reader Comments



fdsfdf
December 26, 2012
dgdfgfdgdfg



Ronky Ponky
April 26, 2013
Pretty good ronky ponky speed tests. Thanks!



Add A Comment





Subscribe to this blog