测试是否存在更快isdefined("arguments.argument")
或为 arguments.argument
设置默认值?
最佳答案
我使用 isDefined()
进行了测试, structKeyExists()
并设置了默认值。我想出了
isDefined - 184ms for 100k iterations
structKeyExists - 149 ms for 100k iterations
Default - 139ms for 100k iterations
因此,看起来设置默认值是最快的选项,但是默认值和
structKeyExists
之间的区别太小了,没关系。我会避免使用 isDefined()
在您的代码中的任何地方。我运行的代码如下。
<cfset loops = 100000>
<cffunction name="myfunc" returntype="void">
<cfargument name="myTest">
<cfif isDefined('arguments.myTest')>
</cfif>
</cffunction>
<cffunction name="myfunc2" returntype="void">
<cfargument name="myTest">
<cfif structKeyExists(arguments,'myTest')>
</cfif>
</cffunction>
<cffunction name="myfunc3" returntype="void">
<cfargument name="myTest" default="">
</cffunction>
<cfset start = getTickCount()>
<cfoutput>
<cfloop from="1" to="#loops#" index="i">
#myfunc()#
</cfloop>
</cfoutput>
<cfdump var="#getTickCount() - start#"><br>
<cfset start = getTickCount()>
<cfoutput>
<cfloop from="1" to="#loops#" index="i">
#myfunc2()#
</cfloop>
</cfoutput>
<cfdump var="#getTickCount() - start#"><br>
<cfset start = getTickCount()>
<cfoutput>
<cfloop from="1" to="#loops#" index="i">
#myfunc3()#
</cfloop>
</cfoutput>
<cfdump var="#getTickCount() - start#">
关于Coldfusion:为参数设置默认值还是使用 isdefined 更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16698732/