473,396 Members | 2,090 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,396 software developers and data experts.

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 17 '05 #1
11 7657
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 17 '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 17 '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 17 '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 17 '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 17 '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 17 '05 #7
Tell me more. How does bounds checking come into it?

Nov 17 '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 17 '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 17 '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 17 '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 17 '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...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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
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
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
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,...

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.