Why is a list loop faster than an array loop?

I’ve always assumed that working with lists was far slower than working with Arrays. It just seems obvious since with an array you have a series of values that are indexed sequentially, whereas with a list you have a string that has to be parsed every time you want to work with it.

I was therefore very surprised to learn that looping over a list is much faster in ColdFusion MX than looping over an array. On average, looping through a 500 item list took one quarter the time required to loop over an array containing the same 500 items. This is certainly counterintuitive and besides, didn’t everyone always say string operations were slow in Java?

After reading the generated Java code I found that when you loop over a list by specifying the list attribute of a cfloop statement, ColdFusion optimizes the code by tokenizing the list only at the outset. If you were to use an indexed loop and listGetAt() each element, then ColdFusion would retokenize the list on each call and you’d start to get serious performance degradation.

So what’s the conclusion? Looping over lists is good, but list operations whenever you’re making more than one call to the list function is bad. At least that my new opinion, subject to change without notice. :-)

One thought on “Why is a list loop faster than an array loop?

  1. This is how flash works:
    An array is implemented by a list with numeric indices. If you access array[index], index is converted to its string representation beforehand. This conversion is expensive.

    Maybe CF works the same ?

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>