Cleanliness in Code: Saving memory on while running a page

There are some really quick and easy ways to save memory in Coldfusion which take very little effort.  Here are some of them:

Empty your variables after using them.

It may seem silly to do this since CF does a rather good job of cleaning up memory after it uses a variable, however you'd be surprised how much memory really gets used by variables. 

A simple example is clearing a variable after calling XML.

 

<cfhttp url="#xml_file#" method="GET" resolveurl="Yes" throwOnError="Yes"/>
<cfscript>
    xmlDoc = XmlParse(CFHTTP.FileContent);
    resources=xmlDoc.xmlroot.xmlChildren;
    num_types=ArrayLen(resources);
    
    data = structNew();
    for(i=1;i LTE num_types;i=i+1){
        id = resources[i].Id.XmlText;
        data[id] = structNew();
        data[id].name = resources[i].Name.XmlText;
    }    
    
    xmlDoc = "";
    resources = "";
    num_types = "";
</cfscript>

It may note seem like much from the code above, but imagine receiving hundreds of pages of XML content. After you're done parsing and processing all of that content, it can still hang in memory through the variable it's stored in, in this case "xmlDoc". By setting this variable to an empty string at the end of the code, that memory is freed up quickly and can even save a process time.

Release your com objects:

Another type of variable that is often neglected after being used is the Object, this can be cleared another way. By using the releaseComObject() function, and passing in an object, the data will be cleared from memory.

If you're going to be working with loops, you'll want to take note of both of these tips especially, because some pesky variables won't do garbage collection (memory cleanup) while a loop is occurring.

Comments
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1.002. Contact Blog Owner