ColdFusion:更高效的 structKeyExists() 而不是 isDefined()
在 ColdFusion 中,哪一个更有效?
isDefined('url.myvar')
或者
structKeyExists(url, 'myvar')
Which of these is more efficient in ColdFusion?
isDefined('url.myvar')
or
structKeyExists(url, 'myvar')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如今(CF8+)速度差异并不是那么很大。然而,structKeyExists 确实要快一些。原因如下。
当您使用
isDefined
时,您传入的字符串将作为键名称在多个范围内进行搜索。从 CF9 开始,范围列表(按检查顺序排列)为: (source)即使您将范围名称与
isDefined
一起使用(例如:if isDefined('variables.foo')
),列表仍然会按顺序检查;如果定义了变量local.variables.foo
,它将在BEFOREvariables.foo
之前找到。另一方面,structKeyExists 只搜索您传递给它的结构以查找键名是否存在;所以它需要寻找的地方要少得多。
在我看来,通过使用更明确的代码(
structKeyExists
),您不仅可以获得一些性能,而且您的代码更具可读性和可维护性。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 variablelocal.variables.foo
is defined, it will be found BEFOREvariables.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.使用更容易阅读并且最能展示您正在做什么的内容。
两者之间的差异小得令人难以置信,而且很可能根本不值得担心。
不要浪费时间优化代码,除非您有经过验证且可重复的测试用例来证明速度缓慢。
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.