Akira wrote:
I noticed that using foreach is much slower than using for-loop, so I
want to change our current code from foreach to for-loop.
But I can't figure out how.
Could someone help me please?
Current code is here:
foreach ( string propertyName in ht.Keys )
{
this.setPropert y( propertyName, ht[propertyName] );
}
In what situation did you see that a foreach loop is slower than a for
loop? There might be a small difference, but I think that you have to
have a very special situation to be able to even measure the difference.
To be able to use a for loop on the keys, you have to copy the keys to
an array to be able to access them by index:
ICollection keyCollection = ht.Keys;
string[] keys = new string[keyCollection.C ount];
keyCollection.C opyTo(keys, 0);
for (int i = 0; i < keys.Length; i++) {
this.setPropert y(keys[i], ht[keys[i]]);
}
This means that the CopyTo method will loop through the buckets in the
hashtable once to copy all the keys, which is about the same as the
enumerator used in the foreach loop does. After that you have another
loop, that, even if it's slightly faster than a foreach loop, never can
make up for the time lost when creating the array.
In this case, the for loop will be very much slower than a foreach loop
because what you are looping through is much better suited for an
enumerator than a counter.
In most cases where you can efficiently use either form of loop, you
will not be able to measure any difference, and in the few cases where
you could measure any difference, I'm not at all sure that it would
always be in the favour of a for loop.
You should use the form of loop that fits best for what you are doing
instead of limiting yourself to the one form that you believe is faster.
Save the cutting edge optimising to the code where it will do any
difference.
/Göran Andersson
_____
http://www.guffa.com