Tales from a Trading Desk

Noise from an Investment Bank

.NET 1.1 C# for vs foreach

Most of us .NET engineers know that for is faster than foreach - here and here. Its thus easy to re-code a foreach to use a for when iterating over a list, string etc.  However, if you want to access all the keys/values in a hashtable, it appears as though you are still forced to you foreach, or am I missing something ?
Posted: Feb 25 2004, 12:06 AM by mdavey | with 4 comment(s)
Filed under:

Comments

Scott Mitchell said:

Yes, you have to do a foreach. If you were able to do a for, then you could do something like this:

for (int i = 0; i < hashTable.Keys.Count; i++)
// do something with hashTable.Keys[i]

This would imply that there is some ordering, that Keys[i] comes *before* Keys[i+1]. But with a hashtable, the ordering is obtruse. Also, and perhaps more of a reason why you can't access a Key/Value ordinally, is that inserting or deleting a value could do "interesting" things to your ordinal understading.

If you are interested in a background on how the hashtable maintains its data internally, check out:
http://msdn.microsoft.com/vcsharp/default.aspx?pull=/library/en-us/dv_vstechart/html/datastructures_guide2.asp
# February 24, 2004 8:11 PM

Mike said:

How about using .GetEnumerator()?
# February 24, 2004 9:27 PM

Jerry Pisk said:

IEnumerable.GetEnumerator is exactly what foreach does.

But I'm curious - how did you come to the conclusion that for is faster than foreach? For strings that might be true, but for generic IEnumerable objects (let's say ones that also implement ICollection and IList, so you can actually write a for loop on them)?
# February 25, 2004 12:15 AM

Matt said:

Check out the performance chapter: http://www.theserverside.net/booksinreview/pag.aspx
# February 25, 2004 8:21 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)