Using "for each" is the same as using "GetEnumerator" -- the compiler
produces the GetEnumerator code for you behind the scenes.
Using for-each is generally recommended over an index loop because the
for-each loop may be able to loop through the collection more
efficiently and also the for-each loop will be more common as not all
collections are numerically indexed and thus an index loop will not
where everywhere a for-each loop is supported.
As for which really runs faster, it depends on the collection. In
your example, the index loop will run faster because the
for-each/GetEnumerator versions have the extra overhead of additional
conditionals and method calls, ensuring concurrency (nobody else
changed the list while you're looping), maintaining an internal index,
and maintaining a reference to both the index and the current value.
The speed difference is negligible though--0.003 seconds on 100,000
rows by my tests.
HTH,
Sam
On Thu, 03 Feb 2005 11:22:56 -0500, C Williams <no****@thank.you>
wrote:
I find myself needing to loop through various collections in .NET a lot.
I am wondering if there is a generally accepted method for doing so.
I see three main ways (I'll use rows in a DataTable, which I am doing a
lot of work with)
1) For each curRow in curTable.Rows
2) For i = 0 to curTable.Rows.Count -1
currow = curtable.rows(i)
3) use curTable.Rows.GetEnumerator
Option 1 yields the shortest code, but which runs the fastest? I
suspect they are very similar, but I also suspect that someone out there
actually *knows*!
Thanks for any insights you have!
-Casey