ColdFusion:更高效的 structKeyExists() 而不是 isDefined()

发布于 2024-09-28 01:52:04 字数 145 浏览 2 评论 0原文

在 ColdFusion 中,哪一个更有效?

isDefined('url.myvar')

或者

structKeyExists(url, 'myvar')

Which of these is more efficient in ColdFusion?

isDefined('url.myvar')

or

structKeyExists(url, 'myvar')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧梦荧光笔 2024-10-05 01:52:04

如今(CF8+)速度差异并不是那么很大。然而,structKeyExists 确实要快一些。原因如下。

当您使用 isDefined 时,您传入的字符串将作为键名称在多个范围内进行搜索。从 CF9 开始,范围列表(按检查顺序排列)为: (source)

  1. 本地(仅限函数本地、UDF 和 CFC)
  2. 参数
  3. 线程本地(仅限线程内部)
  4. 查询(不是真正的范围,适用于查询中的变量循环)
  5. 线程
  6. 变量
  7. CGI
  8. CFFile
  9. URL
  10. 表单
  11. Cookie
  12. 客户端

即使您将范围名称与 isDefined 一起使用(例如:if isDefined('variables.foo')),列表仍然会按顺序检查;如果定义了变量 local.variables.foo,它将在BEFORE variables.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)

  1. Local (function local, UDFs and CFCs only)
  2. Arguments
  3. Thread local (inside threads only)
  4. Query (not a true scope, applies for variables within query loops)
  5. Thread
  6. Variables
  7. CGI
  8. CFFile
  9. URL
  10. Form
  11. Cookie
  12. Client

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.

玩套路吗 2024-10-05 01:52:04

使用更容易阅读并且最能展示您正在做什么的内容。

两者之间的差异小得令人难以置信,而且很可能根本不值得担心。

不要浪费时间优化代码,除非您有经过验证可重复的测试用例来证明速度缓慢。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文