473,473 Members | 1,513 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Enumerator vs ForNext vs ForEach

Hi,

Which is better in terms of performance.

Iterating over Enumerator
ForNext loop (using indexer)
ForEach loop

Thanx
rawCoder
Nov 21 '05 #1
11 1488
I'm guessing the regular for loop with just incrementing a variable.

I guess you can test this pretty easily though without having to ask in a
newsgroup. Just run some tests on large sets of data.

"rawCoder" <ra******@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
Hi,

Which is better in terms of performance.

Iterating over Enumerator
ForNext loop (using indexer)
ForEach loop

Thanx
rawCoder

Nov 21 '05 #2
Hi,

I remember the second was the fastest, but some people claim the 1st is
equally performant (and the 3rd actually implies the 1st with the gluing
code compiled for you in the background).
I'd suggest that you wrote a simple performance test using all these
approaches and post your results here.

Also, you can consult the 'Improving the performance of .NET applications'
e-book (not exact title, should be available from the Patterns and Practices
website).

--
Sincerely,
Dmytro Lapshyn [Visual Developer - Visual C# MVP]
"rawCoder" <ra******@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
Hi,

Which is better in terms of performance.

Iterating over Enumerator
ForNext loop (using indexer)
ForEach loop

Thanx
rawCoder


Nov 21 '05 #3
rawCoder,

It's hard to say. Each implementation of IEnumerable/IEnumerator will
be different. Each collection object can handle enumerations differently.

However, I would think that most implementations will just keep an
internal counter in the implementation of IEnumerator and then access the
collection using that internal counter (which is the same as using a for
each loop). This assumes that the collection is suited for this kind of
iteration (a tree structure would be completely different, for example).

Generally speaking though, it is better to use foreach, because if the
implementation of IEnumerator also implements IDisposable, it will handle
the disposing of the implementation as well.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"rawCoder" <ra******@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
Hi,

Which is better in terms of performance.

Iterating over Enumerator
ForNext loop (using indexer)
ForEach loop

Thanx
rawCoder

Nov 21 '05 #4
The for loop using an indexer can introduce some serious performance
problems, but only in some situations. Take for example iterating over
an array returned by a property:

int numItems = myClass.Property.Length;
for (int i = 0; i < numItems; i++)
{
... do something with myClass.Property[i] ...
}

This can incur a serious performance penalty if myClass builds a return
array for every reference to myClass.Property. However,

foreach (Item t in myClass.Property)
{
... do something with t...
}

incurs no such penalty, because the array is fetched from
myClass.Property once and then the enumerator ranges over the one
array.

(To wit, I'm talking about a property that may look like this:

public class TheClass
{
public Item[] Property
{
get
{
Item[] result = new Item[this._internalArray.Length];
for (int i = 0; i < this._internalArray.Length; i++)
{
result[i] = this._internalArray[i].Clone();
}
return result;
}
}
}

As you can see the array gets copied every time, which makes the for
loop with indexer in the code using this property a real performance
hog!)

Nov 21 '05 #5
rawCoder,

I don't know how it is implemented in dotNet, however in past were things
like foreach often implementing direct the actual address length to add to
the previous.

I never changed my behaviour that I use instructions as foreach when I don't
need an indexer. When that is not done, than I loose nothing, and when that
in future is done, there is only some benefit.

However just a very simple thought,

Cor
Nov 21 '05 #6
from ScaleNet.pdf
Page 251-252
Chapter5: Improving Managed Code Performance ( Collection Guidelines )

Consider for Instead of foreach
Use for instead of foreach (C#) to iterate the contents of arrays or
collections in
performance critical code, particularly if you do not need the protections
offered by
foreach.
Both foreach in C# and For Each in Visual Basic .NET use an enumerator to
provide
enhanced navigation through arrays and collections. As discussed earlier,
typical
implementations of enumerators, such as those provided by the .NET
Framework,
will have managed heap and virtual function overhead associated with their
use.
If you can use the for statement to iterate over your collection, consider
doing so in
performance sensitive code to avoid that overhead.

Just one question? The enumerator discussed in above para .. is it the same
as IEnumerable.GetEnumerator. Because then foreach must be the most slowest
option as in the same section of the document it has one section named
"Consider Enumerating Overhead."

Sorry didnt read it first b4 posting.

HTH
rawCoder

"rawCoder" <ra******@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
Hi,

Which is better in terms of performance.

Iterating over Enumerator
ForNext loop (using indexer)
ForEach loop

Thanx
rawCoder

Nov 21 '05 #7
Tell me more. How does bounds checking come into it?

Nov 21 '05 #8
Bruce Wood <br*******@canada.com> wrote:
Tell me more. How does bounds checking come into it?


In certain cases (which I don't believe are applicable here, as the
value of the property could easily change between iterations) the
compiler can remove a lot of bounds checking. Say you have:

string[] x = ...;
for (int i=0; i < x.Length; i++)
{
string y = x[i];
///
}

The array access x[i] would normally need to go through a bounds check,
to make sure you're not doing x[-1] or x[1000000]. With the above
(common) code, the JIT compiler can spot that there's no way i is ever
going to be outside the bounds of the array, so can eliminate the
bounds check. I suspect this requires that:

1) x is a local variable, or perhaps a readonly variable.
(Otherwise the value could change between the comparison with x.Length
and the array access.)

2) i and x aren't modified within the body of the loop

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 21 '05 #9
What if I redimension x within the loop thus changing it's length?

"Jon Skeet [C# MVP]" wrote:
Bruce Wood <br*******@canada.com> wrote:
Tell me more. How does bounds checking come into it?


In certain cases (which I don't believe are applicable here, as the
value of the property could easily change between iterations) the
compiler can remove a lot of bounds checking. Say you have:

string[] x = ...;
for (int i=0; i < x.Length; i++)
{
string y = x[i];
///
}

The array access x[i] would normally need to go through a bounds check,
to make sure you're not doing x[-1] or x[1000000]. With the above
(common) code, the JIT compiler can spot that there's no way i is ever
going to be outside the bounds of the array, so can eliminate the
bounds check. I suspect this requires that:

1) x is a local variable, or perhaps a readonly variable.
(Otherwise the value could change between the comparison with x.Length
and the array access.)

2) i and x aren't modified within the body of the loop

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 21 '05 #10
Dennis <De****@discussions.microsoft.com> wrote:
What if I redimension x within the loop thus changing it's length?


You can't change the size of an array object - you'd have to set x to a
new value, which comes under the second restriction I mentioned.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 21 '05 #11
Right! You'll find also that in the following, j=11 when the loop exits so
you can't change a value either:

Dim i, j As Integer
Dim k As Integer = 10
For i = 0 To k
j = j + 1
If j = 5 Then k = 15
Next

J will = 11 and k will = 15

"Jon Skeet [C# MVP]" wrote:
Dennis <De****@discussions.microsoft.com> wrote:
What if I redimension x within the loop thus changing it's length?


You can't change the size of an array object - you'd have to set x to a
new value, which comes under the second restriction I mentioned.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 21 '05 #12

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

Similar topics

0
by: Oliver Hopton | last post by:
Hello, I'm trying to write a PageableCollection class which implements paging for me so I don't need to rely on the paging provided by the DataGrid as that generates huge viewstate when bound to...
2
by: Gordon Rundle | last post by:
It drives me nuts that I can't use foreach with an enumerator instance. I would like the following to be functionally identical: foreach (Object o in MyCollection) ... foreach (Object o in...
3
by: Ali Tahbaz | last post by:
I'm having trouble iterating through LinkSources in an Excel workbook using C#. I first wrote the below code in VBA to get a quick, correct result, Dim x As Variant For Each x In...
2
by: Stephanie Stowe | last post by:
Hi. I am trying to understand the weird System.DirectoryServices object model. I have a DirectoryEntry object. I want to enumerate through the PropertyCollection. So I looked at GetEnumerator....
3
by: K.K. | last post by:
I have an instance of type Dictionary<int, string>. What is the type of the enumerator returned by GetEnumerator()? In other words, how would I fill in this blank: Dictionary<int, string>...
11
by: rawCoder | last post by:
Hi, Which is better in terms of performance. Iterating over Enumerator ForNext loop (using indexer) ForEach loop Thanx rawCoder
1
by: Brian Richards | last post by:
I'm experiencing some wierd behavior with a Dictionary<T,U> class using foreach loops, such that the Key returned in the foreach is not contained in the dictionary. code: Dictionary<A, B>...
3
by: ajmastrean | last post by:
I have a bunch of enumerators. I need to pass them into a function that is designed to write all values of any enumerator to the console. For instance... public enum Days : int { Sunday = 1,...
6
by: Michael C | last post by:
I'm reading about Iterators and the article I'm reading states that an enumerator must load all of the objects into memory, which is obviously a big waste if there are a large number of objects and...
3
by: Dave | last post by:
I'm calling string.Split() producing output string. I need direct access to its enumerator, but would greatly prefer an enumerator strings and not object types (as my parsing is unsafe casting...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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...
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
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...
0
muto222
php
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.