Persisting CFCs for Performance


Every time you invoke a component with cfinvoke, the component is loaded. This can have a performance penalty associated with it, especially if the component is very large or initializes a lot of code when it loads.

You can load components into application scope variables and use them from there. This would cause the component to be loaded and compiled into memory only once, and used directly from memory much more quickly from that point on.

Listing 19.4 is an example of the code required to load and invoke our Actors.cfc component from the application scope.

Listing 19.4. persist.cfmPersisting a Component
 <cfobject name="application.cfcActors" component="Actors"> <cfset allActors = application.cfcActors.getAllActors()> <cfoutput>   There are #allActors.RecordCount# actors in the system. </cfoutput> 

There's a potential problem with this code, however. When you're adding something to the application scope, you need to lock it to avoid having something else stomp on your instance while it's being created. A named lock does this job nicely, so let's change our code as shown in Listing 19.5.

Listing 19.5. persist.cfmLocking a Persistent Component
 <cfif not structKeyExists(application, "cfcActors")>   <cflock name="lock_cfcActors" timeout="5" type="exclusive">     <cfobject name="application.cfcActors" component="Actors">   </cflock>     </cfif> <cfset allActors = application.cfcActors.getAllActors()> <cfoutput>   There are #allActors.RecordCount# actors in the system. </cfoutput> 

We don't need to lock the code where we use application.cfcActors, because it doesn't have any data of its own that might change. This does create another challenge for us, thoughwhen we're developing the application, the component only loads once, and if we change the component we'll have to restart the application server to get a new copy. To avoid that problem, I recommend always having a URL parameter that will flush your components without requiring a restart. With that code added, we have Listing 19.6.

Listing 19.6. persist.cfmFlushing a Persistent Component
 <cfif (not structKeyExists(application, "cfcActors")) or isdefined("URL.Flush")>   <cflock name="lock_cfcActors" timeout="5" type="exclusive">     <cfobject name="application.cfcActors" component="Actors">   </cflock>     </cfif> <cfset allActors = application.cfcActors.getAllActors()> <cfoutput>   There are #allActors.RecordCount# actors in the system. </cfoutput> 



Advanced Macromedia ColdFusion MX 7 Application Development
Advanced Macromedia ColdFusion MX 7 Application Development
ISBN: 0321292693
EAN: 2147483647
Year: 2006
Pages: 240
Authors: Ben Forta, et al

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net