Welcome!

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

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.

Conclusion
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.

SIDEBAR
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
@ThingsExpo Stories
SYS-CON Events announced today that AgilePoint, the leading provider of Microsoft-centric Business Process Management software, will exhibit at SYS-CON's 2nd International @ThingsExpo which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. AgilePoint is the leading provider of Microsoft-based Business Process Management (BPM) software products, has 1,300+ on-premise and cloud deployments in 25+ countries and provides the same advanced BPM feature set as J2EE vendors like IBM and Appian for the Microsoft .NET native environment. AgilePoint customer...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
Things are being built upon cloud foundations to transform organizations. This CEO Power Panel at 15th Cloud Expo, moderated by Roger Strukhoff, Cloud Expo and @ThingsExpo conference chair, will address the big issues involving these technologies and, more important, the results they will achieve. How important are public, private, and hybrid cloud to the enterprise? How does one define Big Data? And how is the IoT tying all this together?
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
SYS-CON Events announces a new pavilion on the Cloud Expo floor where WebRTC converges with the Internet of Things. Pavilion will showcase WebRTC and the Internet of Things. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices--computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.