Clearing Up A Little Confusion Regarding StructKeyExists() Vs. IsDefined() While Parsing XML [ColdFusion]

October 3, 2009

Development

This is something really simple that I consistently overlook. When considering or , normally always wins. It’s scope parameter instructs where to look for a particular variable, where as IsDefined() forces Cold Fusion to search through all the scopes. The performance impact is obvious.

A possible exception to this rule, and where my confusion keeps creeping up, is when an Structure for a specific node. Assuming I want to check for the existence of the “name” node given the following simple structure:


<!---

Simple Test XML

--->

<?XML version="1.0" encoding="UTF-8" ?>
<xmlRootNode>
 <extremeHottie>
  <name>Angelina Jolie</name>
 </extremeHottie>
</xmlRootNode>

First, to clear up my own confusion. Name is a child node of extremeHottie so I have to remember that when referring to the XML structure that the node I want is buried two nodes deep (xmlRootNode / extremeHottie). What this means in that the parent node has to be included as part of the structure, and not referenced as part of the key. This is what I keep forgetting.

Now because we have to implicitly state the node path as an the XML Structure to keep StructKeyExists() happy, we could simply use IsDefined() by passing it just the complete node path. See the example code below. The only question then remains, is there some underlining code behind StructKeyExists() that makes it more efficient than IsDefined(), even in this simple case? I’m not sure. I know it might seem like I’m splitting hairs here, but when you’re parsing through pages of XML nodes every little nook you can find a performance boost is worth it.


<!---

Parsing XML

--->

<!--- Assuming XML is assigned to a variables named testXml --->
<cfset xmlRoot = testXml.XmlRoot />

<!--- Node path as part of the structure. Returns YES --->
<cfoutput>#StructKeyExists(xmlRoot.extremeHottie,"name")#</cfoutput>

<!--- Node path as part of the key. Returns NO --->
<cfoutput>#StructKeyExists(xmlRoot,"extremeHottie.name")#</cfoutput>

<!--- In this instance, the case could be made for just using IsDefined(). Returns YES --->
<cfoutput>#IsDefined("xmlRoot.extremeHottie.name")#</cfoutput>
, , , ,

No comments yet.

Leave a Reply