473,661 Members | 2,453 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

For vs. For Each

Is there a performance difference between this:

\\\
Dim i As Integer
For i = 0 to myObject.Contro ls.Count - 1
myObject.Contro ls(i) = ...
Next
///

and this:

\\\
Dim ctl As Control
For Each ctl In myObject.Contro ls
ctl = ...
Next
///

Or is For Each just "prettier"?

Thanks,

Eric
Nov 21 '05
65 3333
an*******@discu ssions.microsof t.com wrote:
Thanks for the post, Nick.

Nick Malik wrote:
I've had folks tell me that 'for' is more efficient than 'foreach' because
of enumerator overhead.

A newbie question...Wher e do enumerators come into play when using For Each?
In addition , since enumerators can only be of type byte, short, int, or
long, what kind of overhead is introduced?


By 'enumerators' Nick was referring to the IEnumerator interface which
is used by the For Each statement to iterate through the collection (For
Each uses and IEnumerable interface to get the IEnumerator).

I think you're confusing the terminology with an enumeration, such as
declared by VB.NET's Enum statement. A completely different animal.

--
mikeb
Nov 21 '05 #11
"mikeb" wrote:
I think you're confusing the terminology with an enumeration, such as
declared by VB.NET's Enum statement. A completely different animal.


That's exactly what I was doing. Thank you for the clarification, Mike &
Terry.

Eric
Nov 21 '05 #12
I disagree that foreach-construct being readonly is a bad thing. Not
to completely disregard Alvin's gripe, but here's my point of view.

Typically, you use foreach to iterate throught the collection.
Adding/Removing items from the collection during this time puts the
collection into a funny mode that others may not be ready to deal
with, what if you have multiple emunerators? (this is very common for
a nested foreach scenario, yes, that'd be O(n^2) ). I believe in C++
STL libraries you can remove current iterated item, but that opens a
can of worms, you always have to worry whether your current item has
been deleted by another thread.

Also, I highly disagree that the for-construct is faster than
foreach-construct. That is only true when you are talking about ARRAY
collection types. In a linked-list implementation, foreach-construct
O(1) would be faster than for-construct O(n) for iterating through a
collection. The fact that the .NET framework collections are almost
solely based on array types may make the statement correct in 90%+ of
the time, but it is not a correct statement to make generally. And,
besides, I wait for generics!

Typically, hashtables are iterated for the entire key/value pairs,
given that accessing the value of a hashtable is O(1), if you need to
iterate through a hastable, it's easier to iterate through the keys
O(n), and grabbing the value as you go O(1). But I can't think of why
anyone would be iterating through a hashtable except may be as a debug
step to see the contents of the hashtable.

jliu - www.ssw.com.au - johnliu.net
Nov 21 '05 #13
"JohnLiu" <jo******@gmail .com> wrote in message
news:37******** *************** ***@posting.goo gle.com...
I disagree that foreach-construct being readonly is a bad thing. Not
to completely disregard Alvin's gripe, but here's my point of view.

Typically, you use foreach to iterate throught the collection.
Adding/Removing items from the collection during this time puts the
collection into a funny mode that others may not be ready to deal
with, what if you have multiple emunerators? (this is very common for
a nested foreach scenario, yes, that'd be O(n^2) ). I believe in C++
STL libraries you can remove current iterated item, but that opens a
can of worms, you always have to worry whether your current item has
been deleted by another thread.

Also, I highly disagree that the for-construct is faster than
foreach-construct. That is only true when you are talking about ARRAY
collection types. In a linked-list implementation, foreach-construct
O(1) would be faster than for-construct O(n) for iterating through a
collection. The fact that the .NET framework collections are almost
solely based on array types may make the statement correct in 90%+ of
the time, but it is not a correct statement to make generally. And,
besides, I wait for generics!

Typically, hashtables are iterated for the entire key/value pairs,
given that accessing the value of a hashtable is O(1), if you need to
iterate through a hastable, it's easier to iterate through the keys
O(n), and grabbing the value as you go O(1). But I can't think of why
anyone would be iterating through a hashtable except may be as a debug
step to see the contents of the hashtable.

jliu - www.ssw.com.au - johnliu.net


With a For n=start to end step loop you would still have to worry if the
current element has been deleted by either this or another thread since the
start end & step are only evaluated once in the loop.

--
Jonathan Bailey.
Nov 21 '05 #14
On 2004-08-11, Alvin Bruney [MVP] <> wrote:
I'll chime in here with my longtime gripe.

The foreach implementation is flawed because the container is marked as
readonly during the iteration. This is a crime in my opinion because it is
*normal to effect a change on the container while iterating especially from
a vb point of view.


I see your point, but look at it from the implementers' point of view.

Making the container read-only allows for very efficient implementations
of the enumerator, and also makes writing new enumerators fairly simple.
Also, it eliminates a real ambiguity to the For Each statement, does
foreach iterate over the original collection, or over the entire
collection as it changes over time?

Dim i As Integer
For Each o as Object in MyCollection
i += 1
If i = 3 Then
MyCollection.In sert(0, new Object())
MyCollection.Ad d(New Object())
End If
Next

What would the iteration be in this case? Should both new objects be
iterated, or neither? Or just one? You could think of some reasonable
rules to apply to arrays, but what about things like hashes where
position doesn't have a fixed meaning? And how is the Enumerator
supposed to keep track of what's happening to the collection? Do we add
some kind of event to the IEnumerable interface? If so, that could turn
into a lot of overhead since the enumerator has to check for changes on
each iteration.

For efficiency's sake, maybe we could have two different enumeration
types, one for mutable containers and one for read-only, but then not
only are you complicating the class library tremendously, but calling
conventions can get strange (since only one of them can use For Each).

David
Nov 21 '05 #15
Can you give some sample applications where this statement of you is true?
Although due to the nature of loops, they oftentimes fall into
the 20 percent of code that consumes 80 percent of the time.


It is in my opinion definitly not with applications where is by instance
screen painting or/and dataprocessing.

It is in my opinion definitly true for applications where is image
processing where not the GDI+ encoding is used.

However that is in my opinion surely not the majority of the applications.

So I am curious in what type of other applications stand alone loops can
consume 80% of the time?

Just my thought,

Cor
Nov 21 '05 #16
> Making the container read-only allows for very efficient implementations
of the enumerator, and also makes writing new enumerators fairly simple.
Also, it eliminates a real ambiguity to the For Each statement, does
foreach iterate over the original collection, or over the entire
collection as it changes over time?
I don't disagree with that. very good point indeed. but, the current
approach makes it impossible to perform simple tasks inherent in UI
programming (like removing multiselects in a listbox for instance). Where
such simple tasks are overly complicated, i believe the design should be
reviewed.
For efficiency's sake, maybe we could have two different enumeration
types, one for mutable containers and one for read-only, but then not
only are you complicating the class library tremendously,
I think it is a reasonable approach. It would just be another way to iterate
a container and it shouldn't complicate matters since it could be made to
appear as an overload

but calling conventions can get strange (since only one of them can use For Each).
That's really a design issue which needs to be hashed out in a way to make
this approach feasible.

--
Regards,
Alvin Bruney
[ASP.NET MVP http://mvp.support.microsoft.com/default.aspx]
Got tidbits? Get it here... http://tinyurl.com/27cok
"David" <df*****@woofix .local.dom> wrote in message
news:slrnchmj96 .j7j.df*****@wo ofix.local.dom. .. On 2004-08-11, Alvin Bruney [MVP] <> wrote:
I'll chime in here with my longtime gripe.

The foreach implementation is flawed because the container is marked as
readonly during the iteration. This is a crime in my opinion because it
is
*normal to effect a change on the container while iterating especially
from
a vb point of view.


I see your point, but look at it from the implementers' point of view.

Making the container read-only allows for very efficient implementations
of the enumerator, and also makes writing new enumerators fairly simple.
Also, it eliminates a real ambiguity to the For Each statement, does
foreach iterate over the original collection, or over the entire
collection as it changes over time?

Dim i As Integer
For Each o as Object in MyCollection
i += 1
If i = 3 Then
MyCollection.In sert(0, new Object())
MyCollection.Ad d(New Object())
End If
Next

What would the iteration be in this case? Should both new objects be
iterated, or neither? Or just one? You could think of some reasonable
rules to apply to arrays, but what about things like hashes where
position doesn't have a fixed meaning? And how is the Enumerator
supposed to keep track of what's happening to the collection? Do we add
some kind of event to the IEnumerable interface? If so, that could turn
into a lot of overhead since the enumerator has to check for changes on
each iteration.

For efficiency's sake, maybe we could have two different enumeration
types, one for mutable containers and one for read-only, but then not
only are you complicating the class library tremendously, but calling
conventions can get strange (since only one of them can use For Each).

David

Nov 21 '05 #17
> Typically, you use foreach to iterate throught the collection.
Adding/Removing items from the collection during this time puts the
collection into a funny mode that others may not be ready to deal
with, what if you have multiple emunerators?
That is a design and implementation issue, not a programming issue.
Iterating a container which can change during iteration is rightly handled
internally by the construct itself and not by the iterating code so there
should be no funny mode. For instance, what's to stop the internal code from
re-adjusting its contents based on the removal or addition of an item on the
fly? This is very basic functionality available in vb if memory serves me
right.

Multiple enumerators can be handled internally thru synchronization means
and this can all be hidden from the programmer so that she is not aware how
the iterating construct is implemented (good design). I think the choice to
implement this construct as readonly must have come down to efficiency over
functionality. That's the only reason I can think of.

--
Regards,
Alvin Bruney
[ASP.NET MVP http://mvp.support.microsoft.com/default.aspx]
Got tidbits? Get it here... http://tinyurl.com/27cok
"JohnLiu" <jo******@gmail .com> wrote in message
news:37******** *************** ***@posting.goo gle.com...I disagree that foreach-construct being readonly is a bad thing. Not
to completely disregard Alvin's gripe, but here's my point of view.

Typically, you use foreach to iterate throught the collection.
Adding/Removing items from the collection during this time puts the
collection into a funny mode that others may not be ready to deal
with, what if you have multiple emunerators? (this is very common for
a nested foreach scenario, yes, that'd be O(n^2) ). I believe in C++
STL libraries you can remove current iterated item, but that opens a
can of worms, you always have to worry whether your current item has
been deleted by another thread.

Also, I highly disagree that the for-construct is faster than
foreach-construct. That is only true when you are talking about ARRAY
collection types. In a linked-list implementation, foreach-construct
O(1) would be faster than for-construct O(n) for iterating through a
collection. The fact that the .NET framework collections are almost
solely based on array types may make the statement correct in 90%+ of
the time, but it is not a correct statement to make generally. And,
besides, I wait for generics!

Typically, hashtables are iterated for the entire key/value pairs,
given that accessing the value of a hashtable is O(1), if you need to
iterate through a hastable, it's easier to iterate through the keys
O(n), and grabbing the value as you go O(1). But I can't think of why
anyone would be iterating through a hashtable except may be as a debug
step to see the contents of the hashtable.

jliu - www.ssw.com.au - johnliu.net

Nov 21 '05 #18
On Wed, 11 Aug 2004 08:21:47 -0500, an*******@discu ssions.microsof t.com
wrote:
Is there a performance difference between this:

\\\
Dim i As Integer
For i = 0 to myObject.Contro ls.Count - 1
myObject.Contro ls(i) = ...
Next
///

and this:

\\\
Dim ctl As Control
For Each ctl In myObject.Contro ls
ctl = ...
Next
///

Or is For Each just "prettier"?


They are almost identical when your collection is some sort of an array.
But if the collection is e.g. linked list, then executing .Controls(n) will
cause your app to traverse through n elements - the bigger n is the slower
it will take to find n-th element. Using enumerators (For Each) is
considerably faster here.

Best regards,
Michal Dabrowski
Nov 21 '05 #19
> I don't disagree with that. very good point indeed. but, the current
approach makes it impossible to perform simple tasks inherent in UI
programming (like removing multiselects in a listbox for instance). Where
such simple tasks are overly complicated, i believe the design should be
reviewed.


good point. I like the idea of a collection object that isn't read-only,
seperate from other types of collections. Didn't another thread mention a
bit of code that Ericgu put out that does exactly this?
Nov 21 '05 #20

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

Similar topics

4
2022
by: Jean-Christophe Michel | last post by:
Hi, I have a stylesheet with an accumulator like this <xsl:param name="new-x"> <xsl:for-each select="anode"> <mynode> <xsl:attribute name="attr"> <xsl:value select="anode/atag" /> </xsl:attribute>
2
2608
by: matatu | last post by:
Hi to everybody, It's possible to exit from a cycle for-each? I have this code: 1: <xsl:for-each select="field"> 2: <xsl:variable name="tagfield" select="@tag"/> 3: <xsl:variable name="pos" select="position()"/> 4: <xsl:for-each select="/root/ass/istance">
3
3048
by: deko | last post by:
Problem: why doesn't this With block work? is it possible to have a For Each loop within a With block? With objWord .Documents.Add Template:=strTemplate, NewTemplate:=False, DocumentType:=0 For Each varBookmark In Array("ReturnAddress", "NameAddressBlock", "Salutation", "FullName") If DLookup(varBookmark, "tblTemplate", "template_ID = " & strTid) = -1 Then
8
1940
by: Floris van Haaster | last post by:
Hi All! I have a question, i have a web application and I store some member information in a variable i declared in a module like: Public some_info_variable as string in module1.vb But when another user comes to my website he is getting the same values from the variable!!!
13
1501
by: tshad | last post by:
Is there a way to run a script or function on entry of each page without having to put a call in each page? Periodically, I find something I want to do each time a page is entered and I have to go into each page and add a line or 2 in my asp.net code. That's a lot of pages and I could easily miss one. For example, I have a user object that I built that I just added a field - LastPageVisited. This was necessary because, apparently,...
6
4835
by: Michael D. Ober | last post by:
In VB 6, the loop iterator v in the following code must be a variant. dim v as variant dim c as new collection for each v in collection ... next v What is the general translation in VB 7.1 and VB 8 Beta 1? Also, is there an easy way to force "v" to be an early bound variable. In VB 6 this can be
6
1822
by: Neal | last post by:
Hi All, I used an article on XSLT and XML and creating a TOC written on the MSDN CodeCorner. ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/dncodecorn/html/corner042699.htm However, it did'nt quite answer all my questions. How would one create a 3 level TOC when each item level / node was differently named (They used Template match and for-each, but the template match worked as on a 3 level structure they usedf the same named xml...
9
2522
by: xmlhelp | last post by:
stuff.XSL: <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:param name="uid"/> <xsl:template match="/"> parameter UID=<xsl:value-of select="$uid"/> <table border="1"> <tr> <xsl:for-each select="row/value=20]">
17
4018
by: The Frog | last post by:
Hello everyone, I am working on an application that can build database objects in MS Access from text files. I suppose you could call it a backup and restore type routine. Accessing the fields, tables, relationships, and indexes is no issue for me via DAO code. The issue I have is that I am not sure which properties are actually necessary / available to set from code for each possible type of field. I have looked fo´r a reference on...
0
24164
ADezii
by: ADezii | last post by:
If you want to visit each item in an Array, you have two alternatives: Use a For Each..Next loop, using a Variant to retrieve each value in turn. Use a For...Next loop, looping from the Lower Bound to the Upper Bound of the Array. For Each...Next seems simpler because you need not worry about retrieving the Lower and Upper Bounds- the loop takes care of that for you. For Each varValue In alngValues j = varValue Next varValue...
0
8432
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
8343
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
8855
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8758
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
8545
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,...
0
8633
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6185
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
4179
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...
0
4346
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.