You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Compilation and Precompilation in CFMX Templates

Compilation and Precompilation in CFMX Templates

Last month I introduced a precompile "batch" file that allowed you to manually compile CFMX templates, saving the penalty paid by the first user to browse a CFMX template after it was created or edited.

But there will be curious folks (and bit-twiddlers) among you who will want to know more - maybe lots more. How much time is this really saving? If it's compiled to disk, how and when does CFMX read it into memory to execute it? What's the cost of that? What happens with CFINCLUDEd files? Where does the compiled code go? Can I look at it? Can I just delete the generated class files instead? How do I determine which class file was generated for which CF template? Can I distribute the compiled code on other servers without the source code?

I'll address these questions and more in this conclusion.

Evaluating the Execution Time
Before going on, it may be helpful to explain something about determining the impact in terms of execution (and other startup) times for running a template. It will be very helpful to turn on the "Report Execution Times" option in the ColdFusion Administrator settings for "Debugging Settings". This will produce a display (see Table 1) at the bottom of a page when executed in a browser.

As in previous releases, you will only see this debugging information if the Administrator has enabled it. Also, if any IP addresses are listed in the "Debugging IP Addresses" page of the Administrator, then you will only see it if you are in that list. If there are no values in that list, all who execute CF templates on the server will see this info. Finally, if you still don't see this information, be sure that your template (or the application.cfm that is called before it) does not have <CFSETTING ShowDebugOutput="no">.

This particular example shows a file called test.cfm, which included a file called test.html, and also had an application.cfm that was called. It also shows a separate value for "startup, parsing, compiling, loading, & shutdown". We'll get to that in a moment. Keep an eye on this set of timing information when trying to evaluate the impact of various choices and settings.

Compilation Doesn't Eliminate All the Waits
So, after reading my previous article you now know how to precompile a template. You've paid the cost of compiling the code to its underlying Java byte code and now it should execute without any parsing/compiling delay (assuming it's not been edited). What if you restart the server? Will the first user really experience no further delay? Not exactly.

You may recall that I said that CFMX writes the compiled code to disk. Did you wonder how it gets from disk into memory, for CFMX to execute? I mentioned at the outset of the previous article that even in ColdFusion 5 and before, the first execution of a template after a server restart would cause CF to interpret the template into "pcode" and then load that into a "template cache". The code was then executed from memory all day, rather than being read from disk (unless the cache filled, in which case the least recently used template would be flushed from the cache). This was a useful solution for making code run as quickly as possible when executed.

CFMX faces the same dilemma. While the compilation of code to a Java class file eliminates the interpretation step the first time the code is executed after each restart, the fact remains that the compiled code needs to be read from disk and loaded into ColdFusion's memory - in that same template cache that existed in previous releases.

The precompile batch file from the previous release does not perform this "load" of the compiled code into CFMX's template cache, so you can't save that time. Similarly, when the server has just been restarted, it will need to be "loaded" into memory. It's just the first user to run the code after restart (or a compile or precompile) that experiences that load time. So be aware that precompiling won't eliminate the entire wait. There's still the time needed to load the code into the template cache the first time it's executed after restart.

Also, be careful in evaluating the impact of these steps. If you watch the precompile.bat file process, you may notice that compiling even a single template seems to take longer than if you simply let CF compile it automatically. The compiler process in the precompile.bat file has some load time itself on the first template it compiles. If only one template is precompiled, you see that time reflected in the time it takes to compile. If multiple files are precompiled at once, you see each individual template taking less time than if it was compiled alone.

Handling Included Files
In my example above I included a test.html file, but what if I had included a cfm file? Do you wonder if there might be an effect on compilation if code in the included file changes? Would you expect ColdFusion to have to recompile the including template?

It does not. Precompiling the including file after the included file has changed isn't necessary. Indeed, if you look at the compile time reported by the precompile tool it will be reported as 0ms. This reiterates the point that CFINCLUDE is a runtime directive, not a compile time one. Many misconstrue that. (Further proof is demonstrated by the fact that the value of the TEMPLATE attribute naming a file in CFINCLUDE can in fact be a variable. It's clearly a runtime directive.)

What's the difference? Say you have a template that includes another and that included file changes often during the day. You will notice a delay in loading the file. But it would have been true in CF 5 and before. Compilation isn't the cause, and precompilation is not the answer. You just need to get CF to reexecute the template so that it runs the CFINCLUDE to detect that changed file and load it into memory. Again, it's a runtime issue.

I've done this and watched the time reported in the debug output on the first execution of the calling template (after the included file has changed). In one example it went from 1000 ms (reported as execution time for the calling template) to 0ms from then on. Note that this change is in the runtime of the template, not its compile time. So it's not really a compilation issue.

What can you do, especially if some automated process is causing updates to the included file? You could add to that automated process (or create another) that simply executes the calling page once after the included file has changed. This could be kicked off via CFSCHEDULE or CFHTTP. The point isn't to save the resulting output in any way (which is an option with these tags), but merely to cause execution of (or in other words to "touch") the calling page so that it does what it needs to do to interpret the change in the included file.

Where Does the Compilation Go?
I also mentioned in the previous article that CFMX compiles your cfm (and cfc) templates into .class files, which are Java byte code files. If you're curious, the files are written to (and executed from) the cfclasses subdirectory of [cfusionmx]\wwwroot\WEB-INF\ directory where CFMX is installed. This occurs whether you are using another Web server or have located your file outside the default wwwroot location. CFMX compiles and runs the code from this cfclasses directory, regardless of the location of the source file.

This is the reason why in the previous article we needed to specify the -webinf directive in the batch file, to tell it to place compiled code there. If it's not placed there, it won't run in CFMX.

Be warned, though, that the file names for these class files may not be at all apparent. A CF template named Setsession.cfm might lead to a class file named cfsetsession2ecfm1011928409.class.

All templates from all directories end up in this one cfclasses subdirectory. They're not stored here in any subdirectories related to their original location. Instead, CF includes a hash of the directory name in that set of numbers after the file name. Keep that in mind when trying to associate a given class file with its original cfm template. The hashing process is a bit convoluted. (See my blog entry of Oct. 5 for more details, at cfmxplus.blogspot.com.)

Perhaps the easiest way to detect which class file goes with which source file is to simply edit the file and then execute (or precompile) it. Look in the cfclasses directory for the most recently created class file. Assuming your server is not too busy with many compilations taking place, it should be pretty easy to associate the classname with the CF source code name.

Saving Java Source Code Produced by CFMX
So that's where the compiled source code goes. But what about seeing the actual uncompiled Java source code that your CF template is converted into? Normally it's of no concern to CF developers what CFMX is doing under the covers in converting our CFML to Java.

For the ardently curious among you, did you know that you can ask CFMX to save the Java code it creates, in source form? You can. It's an undocumented feature, and while I've had no trouble doing it, I must warn that this is something you do at your own risk. Neither I, nor SYS-CON, nor Macromedia accept responsibility for your trying this.

The setting can only be enabled by someone with administrative control of the server, and the setting is also server-wide. It will add a slight additional time to the compile process, so it's not something you'd want to turn on in production. It probably ought not be left on in development either.

You need to edit the file web.xml in the [cfusionmx]\wwwroot\WEB-INF directory. There, if you're familiar with XML files, you'll find a parameter called "coldfusion.compiler.saveJava". Change its value from false to true. Save the file. Restart the server.

Now, whenever a new or recently edited file is compiled (whether automatically by CFMX or by our precompile.bat file), CFMX will also create a ".java" file along with the ".class" file. This ".java" file will be found in that same [cfusionmx]\wwwroot\WEB-INF\cfclasses\ directory as the ".class" files (and will be subject to that same issue of the curious file naming mentioned above).

The Idea of Deleting the Generated Class Files
Some have proposed that instead of precompiling their code they'd just as soon delete the underlying Java class file that was created when it was last compiled. That may seem like overkill, but there are times when it might be worth trying. Just note that, as the previous sections discussed, finding the class file that's associated with a given source template can be challenging. While some may simply delete all the class files, that's certainly overkill.

Don't forget that in the previous article I mentioned there is a -f directive you can pass to the compile process (by modifying the precompile.bat file). That will force a recompile of a file even if CF doesn't think it's necessary. Sometimes that solves the same problem that deleting the class file would solve.

The Dream of Distributing Compiled Code Without Source
Finally, all this talk of creating compiled Java code has excited some. They wonder if they might finally be able to distribute the compiled code without the associated source files. From an intellectual property protection standpoint, this makes sense. Being able to do so is important to those who sell ColdFusion applications. They want their clients to be able to use the code, without them (or their competitors) seeing the actual source code.

Unfortunately, this is not going to happen with the current release of CFMX (if at all). Macromedia has designed the process so that the source code must be present for the file to be loaded. That's an interesting key point. Some were excited by a demo by Ben Forta at last year's DevCon where he was able to delete a source code file and the template continued to run. Some have even noticed that that can still work. Not always, though. Only if the trusted cache setting is enabled.

With what you know from our previous discussion of loading templates and using the trusted cache setting, you may be able to figure out what's happening. If you run a CF template, it's loaded into memory (after being compiled if it changed). Once it's in memory, that's where CF runs it from. And if the trusted cache setting is enabled, then CFMX no longer looks to the source code file to determine if it's changed. Indeed, it also doesn't look to see if it's been deleted.

But if you restart the server, then CF will try to load the template from disk and even with the trusted cache enabled, the first time the template is run, it will look to see if the CF source template has changed since it was last compiled to disk. Only if they disabled that would we be able to truly distribute the source code.

Macromedia folks have further asserted that they won't enable that feature because it's inappropriate to assume that code compiled on one machine would necessarily work on another machine. It's important to note that your ColdFusion code is more than just the underlying Java byte code it's been compiled into. There are libraries that come with CFMX that are called when your code is run. You would at least need to distribute those as well. Whether Macromedia will address this problem for commercial solution developers is still unclear.

The process of compiling and understanding the compilation process for CFMX templates is something that's not well documented. I don't even want to claim to fully understand it. I've encountered some things in preparing this article that still confound me, and since it's undocumented, maybe we can't expect to fully understand it. I just hope that the information shared here will help you, and that it may also motivate Macromedia to decide what aspects of the process they want to make more public.

You could argue that an Admin interface would be a useful addition in doing the compilation process. Perhaps someone has already started working on that. I welcome comments, questions, and concerns you may have about this compilation process. Feel free to e-mail me or post comments below the online version of this article at the www.sys-con.com site.

Trusted Cache Still Applies
I mentioned in the previous article that ColdFusion automatically detects any new or newly edited templates and then automatically compiles them (in CFMX, or interprets them in CF 5 and before). It does this by checking to see if a CF template about to be executed is new or newly updated. And it does this before each invocation of a template, by every user.

That's a rather costly operation, but it's the cost of being able to freely make code changes and see them reflected immediately. If your production environment is designed so that you don't make changes to your code except on a scheduled basis (perhaps overnight), you should enable the "Trusted Cache" setting in the ColdFusion Administrator.

By enabling "Trusted Cache", you're telling ColdFusion that once it loads a program into memory, it should no longer check to see if its underlying source code template has been updated. This will remain in effect until the server is restarted. Sadly, disabling it and re-enabling it does not cause the template cache to be flushed.

One thing that has changed about the "trusted cache" is the specification of its size. Prior to CFMX, the size setting (on the same page in the Administrator) was set in bytes, and it was difficult to calculate an accurate size. Now, the setting is the total number of templates to cache, rather than their size. It still defaults to 1,024.

More Stories By Charlie Arehart

A veteran ColdFusion developer since 1997, Charlie Arehart is a long-time contributor to the community and a recognized Adobe Community Expert. He's a certified Advanced CF Developer and Instructor for CF 4/5/6/7 and served as tech editor of CFDJ until 2003. Now an independent contractor (carehart.org) living in Alpharetta, GA, Charlie provides high-level troubleshooting/tuning assistance and training/mentoring for CF teams. He helps run the Online ColdFusion Meetup (coldfusionmeetup.com, an online CF user group), is a contributor to the CF8 WACK books by Ben Forta, and is frequently invited to speak at developer conferences and user groups worldwide.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

Most Recent Comments
Sven 11/14/02 04:59:00 AM EST
IoT & Smart Cities Stories
Apps and devices shouldn't stop working when there's limited or no network connectivity. Learn how to bring data stored in a cloud database to the edge of the network (and back again) whenever an Internet connection is available. In his session at 17th Cloud Expo, Ben Perlmutter, a Sales Engineer with IBM Cloudant, demonstrated techniques for replicating cloud databases with devices in order to build offline-first mobile or Internet of Things (IoT) apps that can provide a better, faster user e...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
The Founder of NostaLab and a member of the Google Health Advisory Board, John is a unique combination of strategic thinker, marketer and entrepreneur. His career was built on the "science of advertising" combining strategy, creativity and marketing for industry-leading results. Combined with his ability to communicate complicated scientific concepts in a way that consumers and scientists alike can appreciate, John is a sought-after speaker for conferences on the forefront of healthcare science,...
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear these words all day every day... lofty goals but how do we make it real? Add to that, that simply put, people don't like change. But what if we could implement and utilize these enterprise tools in a fast and "Non-Disruptive" way, enabling us to glean insights about our business, identify and reduce exposure, risk and liability, and secure business continuity?
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...