473,778 Members | 1,958 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Recordc ount
rsMain.Filter = "team = '" & rsTeams("team") & "'"
Response.Write "<b>The following people are on the team "&
rsTeams("team") & ":</b><p>"
For j = 1 To rsMain.Recordco unt
Response.Write rsMain("person_ name")
Response.Write "<br>"
rsMain.movenext
Next
If rsTeams.EOF Then Exit For
rsTeams.movenex t
Next


Jul 19 '05 #1
4 7043
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.CreateOb ject("ADODB.Con nection")

objConn.Open "PROVIDER=MSDat aShape;DATA " & stExistingConne ctionString '
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.HTMLEnco de(objRs.Fields (1).Value)

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

Do While Not rsChild.EOF

Response.Write Server.HTMLEnco de(rsChild.Fiel ds(2).Value) &
"<br>"

rsChild.MoveNex t
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******** ******@TK2MSFTN GP11.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.Recordc ount
rsMain.Filter = "team = '" & rsTeams("team") & "'"
Response.Write "<b>The following people are on the team "&
rsTeams("team") & ":</b><p>"
For j = 1 To rsMain.Recordco unt
Response.Write rsMain("person_ name")
Response.Write "<br>"
rsMain.movenext
Next
If rsTeams.EOF Then Exit For
rsTeams.movenex t
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.Team Name
LastTeam = TeamMember.Team
End If

Print TeamMeber.Perso nName
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******** *************@t wister.tampabay .rr.com...
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.Team Name
LastTeam = TeamMember.Team
End If

Print TeamMeber.Perso nName
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******** ******@TK2MSFTN GP11.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.Recordc ount
rsMain.Filter = "team = '" & rsTeams("team") & "'"
Response.Write "<b>The following people are on the team "&
rsTeams("team") & ":</b><p>"
For j = 1 To rsMain.Recordco unt
Response.Write rsMain("person_ name")
Response.Write "<br>"
rsMain.movenext
Next
If rsTeams.EOF Then Exit For
rsTeams.movenex t
Next

Jul 19 '05 #5

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

Similar topics

25
12714
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 increase. Does Python have a limit on the number of nested for-loops? Thanks.
0
1792
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 dict() print combo2(5)
46
9939
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 already in a loop." Then he goes on to portray a contrived example that doesn't tell me under what conditions a nested loop might be favoured as a solution? i.e. what are nested loops useful for? What kinds of algorithms are served by nested loops?...
77
5248
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. Is this because .NET is inherently slower or does the C# compiler merely produce code that is not as well optimized as the C++ compiler?
9
2853
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
3127
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 trying to understand Goto in this contect. PS: This is not homework.
4
2337
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 way I could write this to get both loops to complete fully? I am using the two while loops to pull data from different tables, and insert that data into a list that has html code surrounding each loop. while ($url = mysql_fetch_array($urls,...
13
2702
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
7265
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 <Boolean ExpressionThen Exit For Next If Not <Boolean ExpressionThen Exit For
0
9629
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9470
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10127
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10069
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7475
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4033
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2865
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.