473,659 Members | 2,562 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 #1
65 3332
Hi,

This was discussed a time ago and U think remember that there were almost
no differences,
beside that, this is VERY EASY to check just write an small program and
iterate both ways and see the results

and finally this is a VB.net question, not a C# one, there is no need to
post it on microsoft.publi c.dotnet.langua ges.csharp

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
<an*******@disc ussions.microso ft.com> wrote in message
news:OY******** ******@TK2MSFTN GP11.phx.gbl...
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 #2
In VB6 for a Collection you should use 'for each'. Here (.NET) it probably
doesn't matter.

I suppose you should use 'for each', because its cleaner and might use
optimizations whenever this will be possible. IHMO it looks cleaner too.

- Joris

<an*******@disc ussions.microso ft.com> wrote in message
news:OY******** ******@TK2MSFTN GP11.phx.gbl...
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 #3
There should be very little in the way of performance difference in these
two code snippets, especially as your control numbers are not likely to be
large anyway.

One point to note is that with For Each, you cannot remove the items or add
to the collection while iterating otherwise it complains, however with a for
loop, you can iterate backwards and remove items.


--

OHM ( Terry Burns )
. . . One-Handed-Man . . .
If U Need My Email ,Ask Me

Time flies when you don't know what you're doing

<an*******@disc ussions.microso ft.com> wrote in message
news:OY******** ******@TK2MSFTN GP11.phx.gbl...
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 #4
Anders Hejlsberg: "Generally my answer is, Always use FOR EACH if you can,
because chances are you will have fewer bugs if you use FOR EACH. There are
just more pitfalls with the regular FOR statement. It is true that in some
cases the FOR statement is more efficient. I think the vast majority of
cases, I don’t think you would ever notice. My advice would be, always use
FOR EACH profile your app. If they turn out to be your problem, then change
them to FOR statements, but I don’t think you ever will in real code. I
think FOR EACH is much more expressive, and in theory allows us to optimize
your code more in the future. There are certain optimizations that we will
do, because we can tell that you’re going over the entire collection or
whatever, and so we could, at least in theory, generate even better code. I
would highly recommend FOR EACH unless you really do need the index."

http://msdn.microsoft.com/msdntv/epi...h/manifest.xml
Nov 21 '05 #5
Eric,
In addition to the other comments:

Are you asking about the Controls collection specifically or are you asking
any collection in general?

As each collection type has its own performance characteristics !
(ControlCollect ion, verses ArrayList, verses Collection, verses an Array,
verses HashTable, verses insert your favorite collection here).

I have to ask: Does it really matter which is faster?

I would not worry about which performs better, I would go with which one is
more straight forward, I find the For Each more straight forward, so that is
the one I favor.

Remember that most programs follow the 80/20 rule (link below) that is 80%
of the execution time of your program is spent in 20% of your code. I will
optimize (worry about performance) the 20% once that 20% has been identified
& proven to be a performance problem via profiling (CLR Profiler is one
profiling tool).

For info on the 80/20 rule & optimizing only the 20% see Martin Fowler's
article "Yet Another Optimization Article" at
http://martinfowler.com/ieeeSoftware...timization.pdf

Hope this helps
Jay

<an*******@disc ussions.microso ft.com> wrote in message
news:OY******** ******@TK2MSFTN GP11.phx.gbl...
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 #6
Would you have been happier if Eric has written the question in C#? This is
very much as important a question in C# as it is in VB.NET.

foreach (Control ctl in myObject.Contro ls)
{
// do something useful with 'ctl'

}

I've had folks tell me that 'for' is more efficient than 'foreach' because
of enumerator overhead. For most of my code, however, this is a moot point.
Unless the code is in a critical loop, the difference in processing so tiny
that the improvement in code readability greatly outweighs the overhead of
allowing .NET to manipulate the enumerator.

--- Nick

"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
in message news:%2******** **********@TK2M SFTNGP11.phx.gb l...
<<clipped>>
and finally this is a VB.net question, not a C# one, there is no need to
post it on microsoft.publi c.dotnet.langua ges.csharp
<<clipped>>
<an*******@disc ussions.microso ft.com> wrote in message
news:OY******** ******@TK2MSFTN GP11.phx.gbl...
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 #7
Jay B. Harlow [MVP - Outlook] wrote:
Are you asking about the Controls collection specifically or are you asking any collection in general?
As each collection type has its own performance characteristics !
I just meant collections in general, but you make a good point.
I have to ask: Does it really matter which is faster?
Not on my current projects, but it's good to know for the future.
Remember that most programs follow the 80/20 rule (link below) that is 80%
of the execution time of your program is spent in 20% of your code. I will
optimize (worry about performance) the 20% once that 20% has been identified & proven to be a performance problem via profiling (CLR Profiler is one
profiling tool).


I usually follow the 80/20/100 rule, where I optimize the 20% and give the
remaining 80% a good work over anyway to make sure the aggregate is as
efficient as possible. ;-)

Thanks for your reply, Jay.

Eric
Nov 21 '05 #8
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?

Thanks again,

Eric
Nov 21 '05 #9
He is referring to the Enumerator Interface IEnumerator. See below, you can
create your own.

Public Class Class1
Implements IEnumerator

Public ReadOnly Property Current() As Object Implements
System.Collecti ons.IEnumerator .Current
Get

End Get
End Property

Public Function MoveNext() As Boolean Implements
System.Collecti ons.IEnumerator .MoveNext

End Function

Public Sub Reset() Implements System.Collecti ons.IEnumerator .Reset

End Sub
End Class

--

OHM ( Terry Burns )
. . . One-Handed-Man . . .
If U Need My Email ,Ask Me

Time flies when you don't know what you're doing

<an*******@disc ussions.microso ft.com> wrote in message
news:%2******** **********@TK2M SFTNGP10.phx.gb l...
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?

Thanks again,

Eric

Nov 21 '05 #10

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
1939
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
8428
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
8339
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,...
1
8535
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
8629
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...
0
7360
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6181
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
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4338
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1982
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.