I recently taught a Fast Track to ColdFusion 7 (FTCF7) course and what struck me was the liberal use of the isDefined() function throughout the course material. Now, I confess, I have used the function many times in the past, but now more commonly use the structKeyExists() function. So why does Macromedia and now Adobe, still highlight the isDefined() function when, in my opinion, structKeyExists() is more efficient?
First we need to define what each one does:
IsDefined() evaluates a string value to determine whether the variable named in it exists.
StructKeyExists() determines whether a specific key is present in a structure.
On the Adobe Livedocs website, the documentation highlights the fact that the two functions are interchangeable in several situations, e.g. whenever a structure (i.e. associative array) is used. Now, almost everything is a structure, so that doesn’t help.
IsDefined() checks not just if a variable exists, but if it is also syntactically correct. This clearly has runtime implications. That is why, when dealing with structures you should avoid isDefined() in favour of structKeyExists().
I hope the FTCF8 course moves forward and ditches the liberal use of isDefined() and introduces more examples of alternative functions such as structKeyExists(). All too often I see examples which appear to be the path of least resistence, but not best practice.
Shall I mention the incomplete/non-functioning code examples in the FTCF7 course … !?! That’s another story.
Tags: Adobe, alternatives, best practice, ColdFusion, functions, isdefined(), macromedia, structkeyexists()
-
I also believe there is another performance factor with isDefined. When you execute something like isDefined(“session.user”) is checks other scopes for the key as well such as variables.session.user and request.session.user. I stopped using isDefined() all together years ago now and I’m not sure of a reason why to use it, unless maybe you don’t know what scope the var will be in [variable, form, url].
-
I dropped using isDefined() many moons ago as well, I thought it was common knowledge that isDefined() was inefficient and structKeyExists() was the way to go.
Well, reading around and coming across Marcos Placona’s blog where he has conducted a test, it turns out, to my amazement, structKeyExists() is slower then isDefined()!
The key here is that isDefined() is super-fast when the scope exists, i.e. isDefined(“session.userID”), but mega-slow if a non-existent scope is used, e.g. isDefined(“unknownStruct.userID”).
structKeyExists() is consistent regardless of what you provide.
So, as long as you are asking for a SCOPED variable that is extant, isDefined will be faster on average!
structKeyExists(), may be comparatively slower, but forces scoping, which is good practice.
-
structKeyExists() is the way to go.


3 comments
Comments feed for this article
Trackback link: http://www.simonwhatley.co.uk/isdefined-vs-structkeyexists/trackback