| By Ben Forta | Article Rating: |
|
| August 23, 2000 12:00 AM EDT | Reads: |
8,912 |
ColdFusion features support for several different types of variables you can use in your applications...some types are simpler than others to use. When determining the type to use, simplicity and ease of use shouldn't be the only deciding factors. Use the wrong type...and performance can suffer.
Simple Variables
Let's start with the basics. More often than not you'll find yourself using simple variables. There are essentially three ways to create such variables:
- The <CFSET> tag is used to create or set (overwrite) a variable.
- The <CFPARAM> tag is used to create a variable (with a default value) only if that variable doesn't already exist.
- Assignment within a <CFSCRIPT> block is used in much the same way as the <CFSET> tag.
<CFSET yesterday=DateAdd("d", -1, Now())>To display (or access) simple variables, you just need to refer to it, as follows:
<CFOUTPUT>#DateFormat(yesterday)#Lists
</CFOUTPUT>
Lists are strings that contain one or more elements separated by a specified delimiter. A comma-delimited list of values is obviously a list. A sentence is a list of words delimited by spaces (or other punctuation characters). Even phone numbers can be thought of as lists delimited by hyphens or parentheses.
Lists are actually not a variable type; they're really just simple variables. In truth, any variable can be treated as a list. There are no special functions for creating lists. You'd create one just as you would any simple variable. The following code snippet creates a list of four product IDs:
<CFSET prods="123A,76GH,901HY,91AA">The following code snippet also creates a list, a space-delimited list of words:
<CFSET title="ColdFusion Developer Journal">Accessing specific list elements requires the use of special functions, all of which begin with the word List. ListFirst() returns the first element in a list, ListLast() returns the last and ListGetAt() can be used to obtain any list element by specifying its position. You can even sort, search and edit list elements, all using List functions. But you can't access specific list elements directly for that you must use special functions. To display the third element in the above list you could use the following code:
<CFOUTPUT>#ListGetAt(prods, 3)#</CFOUTPUT>The default list delimiter is a comma, but all List functions take an optional attribute that allows you to specify an alternate delimiter. For example, to count the number of words in a string, you could use the following code:
<CFSET num_words=ListLen(sentence, " ")>Lists are easy to use, and they're especially convenient when working with form field values and SQL statements (both of which also use comma-delimited values). But list access comes with a significant performance overhead. Because lists are actually strings, requesting the third element as we did above requires ColdFusion to parse the string to find that element. ColdFusion can't access that element directly. It must first go through that parse step each time that element is accessed.
Arrays
Arrays are special variable types, usually used to contain related data in a structured and sequential manner. An array is a set of placeholders, each containing a value. And arrays can be multidimensional. ColdFusion supports up to three dimensions, though you'll rarely have use for three-dimensional arrays. A list of values could be stored in a one-dimensional array, while a shopping cart (which needs to contain multiple items, each with multiple properties) could be stored in a two-dimensional array.
Arrays are manipulated using special functions that all begin with the word Array. They're created using the ArrayNew() function, which takes a parameter that specifies the number of dimensions needed. To create a SESSION variable shopping cart as a two-dimensional array, you could do the following:
<CFSET SESSION.cart=ArrayNew(2)>Array elements can be accessed directly by specifying the appropriate index (position). Array[1] refers to the first element in a one-dimensional array, Array[2][3] refers to the third column in the second row in a two-dimensional array (of course, you'd need to use the actual array name, not the word Array as I did). So to assign a value to our shopping cart, you could do the following:
<CFSET SESSION.cart[2][3]=100>To display an array element, you simple refer to it, like this:
<CFOUTPUT>#SESSION.cart[2][3]#Arrays are extremely useful when working with sets of related data, so ColdFusion includes an extensive set of array manipulation functions that do things like sorting, finding high or low values, and much more. And array access is fast. ColdFusion treats arrays like sets of values (unlike lists), and as such is able to access specific array elements without having to perform unnecessary processing or intensive parsing.
</CFOUTPUT>
It's worthwhile to note that two-dimensional arrays are usually thought of as grids, although this isn't technically accurate in ColdFusion. Unlike most other languages, ColdFusion's multidimensional ar-rays are actually arrays of arrays. The difference is subtle. In traditional arrays, if the first row has six columns, then all rows will have six columns (I'm using the terms rows and columns for simplicity's sake only). In ColdFusion arrays grow dynamically and as needed, as do arrays within arrays. So the fact that one row has a certain number of columns doesn't mean that other rows will have the same number. As such, you must always make sure that specific index elements exist before you attempt to use them.
Structures
Structures are one of the most powerful and flexible variables types in ColdFusion. They can be thought of as variables that contain other variables. They have two primary uses:
- Related data can be grouped together for simpler processing.
- Array-style data can be manipulated using element names (called keys) instead of numeric indexes.
As you'd expect, structures are manipulated using CFML functions that all begin with the word Struct. To create a new structure, you'd do the following:
<CFSET customer=StructNew()>To set structure elements, you could do the following:
<CFSET customer.id=100>To display a value in a structure, you simply refer to it by name, like this:
<CFSET customer.first_name="Ben">
<CFOUTPUT>#customer.first_name#You can loop through structures and pass them as tag attributes, and more. In fact, as of ColdFusion 4.5, many of the internal sets of values are actually structures. For example, a structure named FORM contains all form fields, and a structure named URL contains all URL parameters. Thus, when you refer to FORM.name, you're actually ac-cessing a structure member (perhaps without even knowing it).
</CFOUTPUT>
Like arrays, ColdFusion can access structures quickly and efficiently. And like arrays, structures can contain other variable types too (like other arrays or structures). As such, structures are ideally suited for grouping related data, as well as for organizing complex or large data sets. Structures are particularly well suited for use with SESSION and APPLICATION variables. Instead of having lots of what are essentially global variables floating around, you'll perhaps have just one structure that contains all the other data.
Picking Your Type
Lists are easy to use, but ColdFusion processes them far more slowly than it does arrays or structures. While I haven't seen any formal numbers from Allaire on the difference in performance, my own testing (creating massive lists, arrays and structures, then extracting thousands of randomly selected elements from them) indicates that list access is usually as much as three times slower than array or structure access.
Lists are easy to use. If you need to build dynamic SQL WHERE clauses, lists are a must. If you work with form fields that have multiple values, lists (and the List functions) are invaluable. But lists are not well suited for any complex data or more complex processing. That's not what they were designed for. The more you access list members, the more benefit there is to be gained from using arrays or structures instead.
Arrays are ideal for sets of data that can be accessed by index. Structures are ideal for grouping any related data (and structures can also be used as associative arrays arrays accessed by key name rather than by index). Both arrays and structures can contain other arrays and structures, making them as powerful and flexible as they are efficient. But arrays and structures aren't as simple to use as lists.
Some applications are best served by a combined approach. For shopping carts I like using a structure containing an array of structures (within the SESSION scope). One application I developed has a structure called SESSION.shopping. It contains a couple of variables pertaining to the customer (things like customer ID), as well as an array called cart that is the cart itself. The array contains structures, one per item in the cart. So the customer ID can be accessed as SESSION.shopping.id, the cart as SESSION.shopping.cart, the third item in the cart as SESSION.shopping.cart[3] and the quantity associated with that item as SESSION.shopping.cart[3].quantity.
Summary
With ColdFusion there's always more than one way to do just about anything. You're the one who has to decide what solution will work best for you. Inevitably, making decisions involves trade-offs. Often the simplest option isn't the most efficient but on the other hand, there's something to be said for simplicity.
The bottom line is this: all of ColdFusion's variable types are useful, and all have their strengths and weaknesses. Your job is to understand these strengths and weaknesses so the design decisions you make are educated and informed ones.
Published August 23, 2000 Reads 8,912
Copyright © 2000 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Ben Forta
Ben Forta is Adobe's Senior Technical Evangelist. In that capacity he spends a considerable amount of time talking and writing about Adobe products (with an emphasis on ColdFusion and Flex), and providing feedback to help shape the future direction of the products. By the way, if you are not yet a ColdFusion user, you should be. It is an incredible product, and is truly deserving of all the praise it has been receiving. In a prior life he was a ColdFusion customer (he wrote one of the first large high visibility web sites using the product) and was so impressed he ended up working for the company that created it (Allaire). Ben is also the author of books on ColdFusion, SQL, Windows 2000, JSP, WAP, Regular Expressions, and more. Before joining Adobe (well, Allaire actually, and then Macromedia and Allaire merged, and then Adobe bought Macromedia) he helped found a company called Car.com which provides automotive services (buy a car, sell a car, etc) over the Web. Car.com (including Stoneage) is one of the largest automotive web sites out there, was written entirely in ColdFusion, and is now owned by Auto-By-Tel.
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Adobe Flex Developer Earns $100K in New York City
- Adobe LiveCycle Enterprise Suite 2 for Cloud Computing
- Adobe Betas Target RIAs and Cloud Computing
- Adobe Cans Another 9% of its Workforce
- Moyea DVD4Web Converter V2.0 Converts DVD to FLV Fast and Synchronously with Watermarks
- Adobe Fiddles with its Web Apps
- Adobe & Salesforce Cut Cloud Deal
- Hosting.com Launches ColdFusion 9 in the Cloud
- The Real Time Infrastructure Ultimatum
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Eval JavaScript in a Global Context
- Fig Leaf Software to Exhibit at Government IT Conference & Expo
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Is Microsoft as Free as Open Source?
- Adobe Reader Sued
- The Planet Named “Bronze Sponsor” of Cloud Computing Expo
- Microsoft Expression Web Has Got Game
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Adobe Flex Developer Earns $100K in New York City
- Bruce Chizen Joins Voyager Capital as Venture Partner
- My Top Seven Wishes From Adobe MAX 2009
- The Next Programming Models, RIAs and Composite Applications
- Where Are RIA Technologies Headed in 2008?
- Constructing an Application with Flash Forms from the Ground Up
- AJAX World RIA Conference & Expo Kicks Off in New York City
- CFEclipse: The Developer's IDE, Eclipse For ColdFusion
- Personal Branding Checklist
- Adobe Flex 2: Advanced DataGrid
- Has the Technology Bounceback Begun?
- Building a Zip Code Proximity Search with ColdFusion
- i-Technology Viewpoint: We Need Not More Frameworks, But Better Programmers
- The Asynchronous CFML Gateway
- Web Services Using ColdFusion and Apache CXF




























