ColdFusion: More efficient structKeyExists() instead of isDefined()

血红的双手。 提交于 2019-11-30 16:27:21

问题


Which of these is more efficient in ColdFusion?

isDefined('url.myvar')

or

structKeyExists(url, 'myvar')

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3956324/coldfusion-more-efficient-structkeyexists-instead-of-isdefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!