Reputation: 3320
Which of these is more efficient in ColdFusion?
isDefined('url.myvar')
or
structKeyExists(url, 'myvar')
Upvotes: 22
Views: 8121
Reputation: 19804
These days (CF8+) the difference in speed is not that great. However, structKeyExists
is indeed a little faster. Here's why.
When you use isDefined
, the string you pass in is searched for as a key name in several scopes. As of CF9, the list of scopes, in the order checked is: (source)
Even if you use the scope name with isDefined
(like: if isDefined('variables.foo')
) the list will still be checked in order; and if the variable local.variables.foo
is defined, it will be found BEFORE variables.foo
.
On the other hand, structKeyExists
only searches the structure you pass it for the existence of the key name; so there are far fewer places it will have to look.
By using more explicit code (structKeyExists
), not only are you gaining some performance, but your code is more readable and maintainable, in my opinion.
Upvotes: 42
Reputation: 112160
Use the one which is easier to read and best shows what you're doing.
The difference between the two is incredibly small, and very likely not worth worrying about at all.
Don't waste time optimising code unless you have a proven and repeatable test case which demonstrates the slowness.
Upvotes: 13