Greg's Blog

helping me remember what I figure out

Scoping Your Variables

| Comments

One small way to improve the performance of your Cold Fusion application is to prefix your variables with it’s scope. What is scoping/prefixing? Essentially you name your variables as per usual and you append a prefix. Say you wanted to create a session variable called userid, you create it by the prefix session. This would result in you declaring your variable as such:

<cfset session.userid = 1 />

Now session variables require you to scope them, but form variables (i.e. those submitted by a form) don’t. So you can refer to a submitted form field by either using it’s name: userid or : form.userid. Why would you do that? Well if you just declare a variable and then call it without defining it’s prefix, then the application server has to traverse all the scopes until it finds the value you are calling and it also does this in a set order. Listed below are all the scopes and the order the application server evaluates them in

  1. query results - queryname.variable
  2. local variables - local.variable
  3. cgi variables - cgi.variable
  4. file variables - file.variable
  5. url variables - url.variable
  6. form variables - form.variable
  7. cookie variables - cookie.variable

These prefixes are not necessarily required by your variables, but it certainly can improve performance and also avoid any confusion (and errors) should you have two identically named variables in different scopes as with the example above, where I declared a session.userid and a form.userid variable. Scoping allows you and the application server to easily identify them. There are 5 other scopes where a prefix is required, these are: server, application, session, request and attributes but more about these in later tidbits. In the meantime make your life easier and avoid possible trappings by scoping them!