StringBuffer vs. List

Friday, July 25th, 2008

Just a quick tip that Shayne pointed out to me (after I had spent a few minutes staring at my code), use StringBuffer if you ever need to have a modifiable string.

Coldfusion uses the Java String class rather than StringBuffer. This means that everytime you modify a string, ColdFusion creates a copy of it in the background and doesn’t de-allocate the old one. Obviously this can quickly eat through your server’s memory. If you plan on only doing a few string modifications (or never modifying it), go ahead and use ColdFusion’s built in string class. Otherwise it will be better to use a StringBuffer.  If you ever want to use a StringBuffer object as a normal ColdFusion string, just use the StringBuffer’s toString() method.

Another benefit to StringBuffer is the number of functions available to you for things like substrings and treating the string as an array.  For a good example of replacing a ColdFusion string with a StringBuffer see this post.

Order in != order out

Thursday, July 24th, 2008

Because arrays in Coldfusion are based off of the vector collection in Java, they don’t always maintain their order in every instance.  If you use ArrayToList(), the order of the list returned will come out in whatever random order it happens to be stored in memory.  If you want a quick demonstration, use the following code:

<cfdump var="#ListToArray(StructKeyList(Variables))#" />

Just keep refreshing the page and you will see the order of the array keep changing.

To get around the weirdness with this, try using the java vector’s methods instead of CF’s array methods.  Just remember that the java methods use zero based arrays (versus CF using one based arrays).

Edit: That example isn’t entirely accurate. Scope variables are based off of abstract maps, but the concept is the same.