Notes from the field on ColdFusion (or related) technical issues.

Wednesday, March 30, 2005

Avoid Evaluate()

The ColdFusion Evaluate() function is often used to resolve dynamically named variables, such as form variables.

The evaluate function, however, forces ColdFusion to compile the expression being evaluated every time you call it, which can be a strain on performance, especially since parts of the compilation process are necessarily single-threaded.

Almost all instances of Evaluate() can be avoided by using structure syntax; instead of writing:

<cfset value=evaluate("form.field#i#")>

You can write:

<cfset value=form["field#i#"]>

Which is much faster, and better yet, simpler.

This doesn't work quite so well when looping over a query, however. If you use structure syntax to access a query column, you must also specify the row number. So, where this would work:

<cfoutput query="q">
#evaluate("q.#fieldname#")#<br>
</cfoutput>

You'd have to use q.currentrow to get the correct row when avoiding evaluate():
<cfoutput query="q">
#q[fieldname][q.currentrow]#<br>
</cfoutput>

Update: 7Apr2005

Classes created for evaluate() [and de() and setVariable()] are cached on a literal string basis (sorta like cached queries work for the exact string of the query), so the performance impact isn't quite so bad, so long as the literal string for evaluate() doesn't change every time.

5 comments:

  1. I've been reading that it's important to avoid evalute() in CF, but what about an include situation where the code calls for a variable to be evaluated and that variable may come from a form OR it might come from a query?

    e.g.

    < input name="#tmpFieldID#" type="text" class="inputText" id="#tmpFieldID#" value="#evaluate(tmpFieldValue)#" >

    ReplyDelete
  2. @yebill

    I know its way out of date. I found this blog because I was trying to put people off Evaluate.

    the answer is value="#variables["#tmpFieldValue#"]#"/>

    It could get difficult within a cfc having used a var... maybe if you need to interpret it using a variable in an array/structure would be better.

    Cheers,
    Joel

    ReplyDelete
  3. I'm just not able to solve this issue..


    An error occurred while evaluating the expression:


    reasona_defined = #evaluate(""reasona_"" & form.dietchoice)#

    An error has occurred while processing the expression:

    reasona_

    ReplyDelete
  4. kanika,

    sounds like form.dietchoice is defined as "" and therefore cf is evaluating reasona_ which doesnt exist

    would still say use
    variables["reason_#form.dietchoice#"]

    and you might want to default it if it wasn't given a default value.

    - Joel

    ReplyDelete