Pergunta

I have a query which retrieves Some data. I want to display that data considering some conditions in different div tags. Now my question is, I am doing this by looping the query once and getting the data in three different structs and using these structs while displaying. Is this a good approach or looping through the query everytime in each div to check the condition is the rirht approach ?

     <tr >
<td >
  features:
 </td>
 <td >
    <cfloop query="getAttributes">
      <cfif getAttributes.type_id EQ 1>
        #getAttributes.seat#<br>
      </cfif>
    </cfloop>
 </td>
</tr>
<tr>
 <td >
  Disclosures:
 </td>
 <td >
    <cfloop query="getAttributes">
   <cfif getAttributes.type_id EQ 2>
          #getTicketAttributes.seat#<br>
   </cfif>
  </cfloop>
  </td>
 </tr> 

Or can i use the below approach

seatStruct 
disclosureStruct 
<cfloop query="getAttributes">  
<cfif getAttributes.type_id EQ 1> 
Insert seatStruct 
<cfelseif getAttributes.type_id EQ 2> 
insert disclosureStruct 
</cfif> 
Now use these structs to display
Foi útil?

Solução

I think you'll have to edit your question a little bit, put some example.

Less looping is always the best approach :) Less conversion if not necessary is best approach :)

If your data is in one query, than there's no need to loop more than once, I guess...

Outras dicas

The best approach will always depend on your specific problem.

Although fewer loop iterations will always result in faster performance, sometimes it can be acceptable to sacrifice some performance for the sake of improved readability.

Maintenance costs are usually the most expensive part of software, so it is worthwhile to make your code easy to read.

In this specific case:

  • Unless the getAttributes query result is unusually large (like over 10000 rows) or this page is loaded unusually often (like more than once/sec), it probably won't make a noticeable difference how many times you loop over it.

  • Both options will take exactly the same amount of time, anyways: The first option loops over the query twice. The second option loops through the query once to populate two structs, then your display code loops through each of the generated structs (which combined have the same number of elements as the query has rows), resulting in the same exact number of total iterations (equivalent to getAttributes.recordcount*2).

  • The code that splits the query results up into different structs is somewhat unusual, thus decreasing readability and increasing maintenence costs. Since it doesn't actually improve performance, it is entirely counter-productive and should not be used.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top