I recently posted about how the MOD (modulus) operator could be used in ColdFusion to determine even and odd rows of an outputted query. Tony Petruzzi commented that this could also be done using bitwise manipulation and, in particular, the ColdFusion BitAnd() function.
For those of you who don't know how bits come into play when we are talking about numbers, the 10 second run down is that every number is represented by a combination of bits. Of these bits, 8 make up a byte. Each bit can be either 1 or 0 (zero). The order and toggling of these bits determines what numeric value the byte represents. Each bit in the byte represents a "place" in the number. Each place that is turned on (value of 1) is "summed" to get the resultant number.
There's a lot more to it, but anyway, the point here is that Tony Petruzzi raised a good point: using MOD actually requires the ColdFusion server to do a lot of division. Division is more expensive in terms of processing than Bitwise manipulation, which really doesn't require much calculation at all. He recommended performing:
BitAnd( QUERY_ROW, 1 )
This will Bit-AND the "ones" bit with the row number. Since only every other number (even vs. odd) has the ones place turned on, then Bit-ANDing it with one will result in TRUE for every other row. To test this, let's try this:
<!--- Loop over the index loop. This could just have easily been a query loop where we were using QUERY.CurrentRow instead of intI. ---> <cfloop index="intI" from="1" to="10" step="1"> #intI# : <cfif BitAnd( intI, 1 )> Odd <cfelse> Even </cfif> </cfloop>
That gives us the following output:
1 : Odd
2 : Even
3 : Odd
4 : Even
5 : Odd
6 : Even
7 : Odd
8 : Even
9 : Odd
10 : Even
This is sneaky little trick. I like it. As he pointed out, you can read more about it over on the ColdFusion Cookbook. I am not sure how the bitwise manipulation happens under the hood, but hopefully it is something that is short-circuited so that the second negative it hits will result in an overall FALSE; if this were the case, it would only ever have to Bit-AND two bits (the "one" column of both numbers).
Want to use code from this post? Check out the license.