Is a CFLOOP really needed?

 
Feb 11, 2004

by Michael Dinowitz

I just answered a question for someone on the Macromedia forums and it reminded me of an issue of style that I've wanted to write about. The poster wanted a 6 digit random number. Easy to do using 6 RandRange() functions in a row. I posted it this way:

<CFSET iSixDigit = RandRange(0,9)&RandRange(0,9)&RandRange(0,9)&RandRange(0,9)&RandRange(0,9)&RandRange(0,9)>		

Another poster did it this way:

<cfset no = "">
<cfloop index="i" from="1" to="6">
<cfset no = no & RandRange(0,9)>
</cfloop>

Now, obviously they both work but there's a big difference between them. The second version looks more elegant than mine. If you were looking at the two solutions, you'd go with the second because it just looks like it's better (and if it was for a job, hire the writer of the second).

So why did I, a rather high level ColdFusion programmer do it my way? Because it saves on processing operations. In my case, I've got 1 CFSET operation and 6 function calls. In the loop case, there's 7 CFSET operations, 6 function calls as well as a CFLOOP. That's a few more operations than what's really needed (IMO).
I've seen a lot of these type things over the years and I've always felt that they were wasteful. Yes, I know it's probably less than a fraction of a millisecond, but it's still processing time.

Update: A new, cleaner and more efficient solution was just posted to the thread.

<CFSET iSixDigit = NumberFormat(RandRange(0,999999), '000000')>

This is a total of 1 CFSET and 2 function calls. Very nice.

Add a Comment
(If you subscribe, any new posts to this thread will be sent to your email address.)
  
Privacy | FAQ | Site Map | About | Guidelines | Contact | Advertising | What is ColdFusion?
House of Fusion | ColdFusion Jobs | Blog of Fusion | AHP Hosting