473,395 Members | 1,689 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Nested For Loops

dw
Hello all. We're doing a site with teams and their members. We've got a page
where we need to display people according to who belongs to a which team.
I've heard that nested loops are bad, but what's the alternative? Would a
group-by clause in the SELECT do the trick? Right now we're doing:

(pseudo-code)---------------------------------
For each team
print team name
For each peson
print person name
Next
Next

(actual code)-----------------------------------
For i = 1 to rsTeams.Recordcount
rsMain.Filter = "team = '" & rsTeams("team") & "'"
Response.Write "<b>The following people are on the team "&
rsTeams("team") & ":</b><p>"
For j = 1 To rsMain.Recordcount
Response.Write rsMain("person_name")
Response.Write "<br>"
rsMain.movenext
Next
If rsTeams.EOF Then Exit For
rsTeams.movenext
Next


Jul 19 '05 #1
4 6987
I don't know that nested loops are bad, but nested loops over recordsets
with filtering could probably be done a more efficiemt way.

Have a look at the MSDataShape Provider. It could help you out here and
remove the need for filtering.

Something like this would return you one recordset, with a child recordset
in the last field position of the first recordset.

SHAPE {select * from customers}
APPEND ({select * from orders} AS rsOrders
RELATE customerid TO customerid)

This would give some ASP something like this....

Dim objConn, objRs, rsChild

Set objConn = Server.CreateObject("ADODB.Connection")

objConn.Open "PROVIDER=MSDataShape;DATA " & stExistingConnectionString '
Assumes your connection string starts with the word PROVIDER

stSql = "SHAPE {select TeamID, TeamName from Teams} APPEND ({select TeamID,
TeamMemberID, TeamMemberName from TeamMembers} AS Whatever RELATE TeamID TO
TeamID) "

Set objRs = objConn.Execute(stSql, , adCmdText)

If Not objRs.EOF Then
Do While Not objRs.EOF

Response.Write "<p>" & Server.HTMLEncode(objRs.Fields(1).Value)

Set rsChild = objRs.Fields(2).Value
If Not rsChild.EOF Then
Response.Write "<blockquote>"

Do While Not rsChild.EOF

Response.Write Server.HTMLEncode(rsChild.Fields(2).Value) &
"<br>"

rsChild.MoveNext
Loop
Response.Write "</blockquote>"
End If

Set rsChild = Nothing

Response.Write "</p>"

objRs.MoveNext
Loop
End If

objRs.Close
Set objRs = Nothing
objConn.Close
Set objConn = Nothing
"dw" <co***************@uncw.edu> wrote in message
news:uj**************@TK2MSFTNGP11.phx.gbl...
Hello all. We're doing a site with teams and their members. We've got a page where we need to display people according to who belongs to a which team.
I've heard that nested loops are bad, but what's the alternative? Would a
group-by clause in the SELECT do the trick? Right now we're doing:

(pseudo-code)---------------------------------
For each team
print team name
For each peson
print person name
Next
Next

(actual code)-----------------------------------
For i = 1 to rsTeams.Recordcount
rsMain.Filter = "team = '" & rsTeams("team") & "'"
Response.Write "<b>The following people are on the team "&
rsTeams("team") & ":</b><p>"
For j = 1 To rsMain.Recordcount
Response.Write rsMain("person_name")
Response.Write "<br>"
rsMain.movenext
Next
If rsTeams.EOF Then Exit For
rsTeams.movenext
Next

Jul 19 '05 #2
> Hello all. We're doing a site with teams and their members. We've got a
page
where we need to display people according to who belongs to a which team.
I've heard that nested loops are bad, but what's the alternative? Would a
group-by clause in the SELECT do the trick? Right now we're doing:

(pseudo-code)---------------------------------
For each team
print team name
For each peson
print person name
Next
Next


Yes, a group by clause would do the trick, but using a group-by clause and
then caching the output would do the trick, better:

If IsCacheExpired(CacheDataKey, CacheExpireKey, ExpireInterval) Then
Dim LastTeam
For Each TeamMember

If LastTeam <> TeamMember.Team Then
Print TeamMember.TeamName
LastTeam = TeamMember.Team
End If

Print TeamMeber.PersonName
Next
End If

Assuming here that IsCacheExpired( ) checks an Application (or session
depending on the scope) variable to see if the cache is expired.
IsCacheExpired uses the CacheDataKey to hold the actual value in
Application, and uses CacheExpireKey to check if the cache needs to be
refreshed, and uses ExpireInterval to calculate the next expire date. You
may also want to keep a list of Keys around incase you want to release the
entire cache when data is written to the database. We also use several
Constants to indicate the refresh interval. For example:

Const CRI_FAST = 1 '// 1 hour
Const CRI_SLOW = 6 '// 6 hours
Const CRI_DAY = 23 '// 1 day

This allows us to change the meaning of a FAST refresh without looking
through every line of code to change a 1 to a 2. Our algorithm uses hours as
the unit of measure, but that is just our implementation.

An even better way to do this would be to save the keys in some sort of
resource, such as an XML file. This way, the refresh interval, CacheDataKey,
and CacheExpire key will be bound together by one single ID, and can be
referenced as such. Then you would just need a list of constants for the
ID's.

If you are doing performance tweaking, I highly recomend this page:
http://msdn.microsoft.com/library/de...ml/asptips.asp

And this one for String optimizations:
http://msdn.microsoft.com/library/de...aspstrcatn.asp

And this one for ADO & SQL:
http://msdn.microsoft.com/library/de...l/BestPrac.asp
HTH,
Jeremy
Jul 19 '05 #3
dw
Thank you, David and Jeremy. Very useful answers. Thanks :-)

"Jeremy" <th***********@hotmail.com> wrote in message
news:dB*********************@twister.tampabay.rr.c om...
Hello all. We're doing a site with teams and their members. We've got a page
where we need to display people according to who belongs to a which team. I've heard that nested loops are bad, but what's the alternative? Would a group-by clause in the SELECT do the trick? Right now we're doing:

(pseudo-code)---------------------------------
For each team
print team name
For each peson
print person name
Next
Next


Yes, a group by clause would do the trick, but using a group-by clause and
then caching the output would do the trick, better:

If IsCacheExpired(CacheDataKey, CacheExpireKey, ExpireInterval) Then
Dim LastTeam
For Each TeamMember

If LastTeam <> TeamMember.Team Then
Print TeamMember.TeamName
LastTeam = TeamMember.Team
End If

Print TeamMeber.PersonName
Next
End If

Assuming here that IsCacheExpired( ) checks an Application (or session
depending on the scope) variable to see if the cache is expired.
IsCacheExpired uses the CacheDataKey to hold the actual value in
Application, and uses CacheExpireKey to check if the cache needs to be
refreshed, and uses ExpireInterval to calculate the next expire date. You
may also want to keep a list of Keys around incase you want to release the
entire cache when data is written to the database. We also use several
Constants to indicate the refresh interval. For example:

Const CRI_FAST = 1 '// 1 hour
Const CRI_SLOW = 6 '// 6 hours
Const CRI_DAY = 23 '// 1 day

This allows us to change the meaning of a FAST refresh without looking
through every line of code to change a 1 to a 2. Our algorithm uses hours

as the unit of measure, but that is just our implementation.

An even better way to do this would be to save the keys in some sort of
resource, such as an XML file. This way, the refresh interval, CacheDataKey, and CacheExpire key will be bound together by one single ID, and can be
referenced as such. Then you would just need a list of constants for the
ID's.

If you are doing performance tweaking, I highly recomend this page:
http://msdn.microsoft.com/library/de...ml/asptips.asp
And this one for String optimizations:
http://msdn.microsoft.com/library/de...aspstrcatn.asp
And this one for ADO & SQL:
http://msdn.microsoft.com/library/de...l/BestPrac.asp

HTH,
Jeremy

Jul 19 '05 #4
Maybe I'm missing something but it seems to me that it would be simpler to
join the tables and order by team name

make a single pass through the data and output the "team heading" when the
team name changes.

strTeam = ""

while not rsdata.eof

if strTeam <> rsdata("team") then
'out put team name and message here
strTeam = rsData("team")
end if

'output team member info here.

loop

--
Mark Schupp
Head of Development
Integrity eLearning
www.ielearning.com
"dw" <co***************@uncw.edu> wrote in message
news:uj**************@TK2MSFTNGP11.phx.gbl...
Hello all. We're doing a site with teams and their members. We've got a page where we need to display people according to who belongs to a which team.
I've heard that nested loops are bad, but what's the alternative? Would a
group-by clause in the SELECT do the trick? Right now we're doing:

(pseudo-code)---------------------------------
For each team
print team name
For each peson
print person name
Next
Next

(actual code)-----------------------------------
For i = 1 to rsTeams.Recordcount
rsMain.Filter = "team = '" & rsTeams("team") & "'"
Response.Write "<b>The following people are on the team "&
rsTeams("team") & ":</b><p>"
For j = 1 To rsMain.Recordcount
Response.Write rsMain("person_name")
Response.Write "<br>"
rsMain.movenext
Next
If rsTeams.EOF Then Exit For
rsTeams.movenext
Next

Jul 19 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
by: chad | last post by:
I am writing a program to do some reliability calculations that require several nested for-loops. However, I believe that as the models become more complex, the number of required for-loops will...
0
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # David Eppstein of the Geometry Junkyard fame gave this elegant # version for returing all possible pairs from a range of n numbers. def combo2(n): return...
46
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are...
77
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop....
9
by: Gregory Petrosyan | last post by:
I often make helper functions nested, like this: def f(): def helper(): ... ... is it a good practice or not? What about performance of such constructs?
5
by: =?Utf-8?B?QUEyZTcyRQ==?= | last post by:
Could someone give me a simple example of nested scope in C#, please? I've searched Google for this but have not come up with anything that makes it clear. I am looking at the ECMA guide and...
4
by: toddlahman | last post by:
I am using two while loops that are nested. The first loop (post name) returns the full column of results, but the second (post modified) only returns the first row of the column. Is there another...
13
by: Fredrik Lundh | last post by:
Patrol Sun wrote: so why exactly are you trying to nest 20 or 100 for-in loops? </F>
8
by: Nathan Sokalski | last post by:
I have several nested For loops, as follows: For a As Integer = 0 To 255 For b As Integer = 0 To 255 For c As Integer = 0 To 255 If <Boolean ExpressionThen <My CodeElse Exit For Next If Not...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.