473,395 Members | 1,762 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,395 software developers and data experts.

How to loop through Hashtable keys without using foreach

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.setProperty( propertyName, ht[propertyName] );
}

Feb 1 '07 #1
3 33326
On Feb 1, 8:56 am, "Akira" <a...@regonline.comwrote:
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.setProperty( propertyName, ht[propertyName] );

}
You "noticed" that using foreach is "much slower" than using a for
loop?

How did you "notice" that? Did you test your application and discover
that the foreach was taking too much time? Did you try it with a "for"
loop and discover that it was faster? Or is this just something you
read somewhere?

For collections, "foreach" is generally a better solution than "for":
it's easier to read, and it's often faster, because the operation
"find the next item" in a collection is often (but not always) faster
than "find the nth item". (The exception is collections like arrays,
in which the two operations differ little, if at all, in speed.)

On top of all of this, I am very, very doubtful that the act of
fetching the next element to process is somehow so costly that it
contributes more to the overall execution time than, say, whatever
you're doing with that next element once you have it. In my
experience, optimizing things like foreach vs for is a waste of time,
*unless* you have benchmarked your program and discovered that it is
in fact a problem.

Feb 1 '07 #2
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.setProperty( 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.Count];
keyCollection.CopyTo(keys, 0);
for (int i = 0; i < keys.Length; i++) {
this.setProperty(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
Feb 1 '07 #3

The problem isn't the foreach but how you're using the data. You're
looping through the keys and then again looking up each value by key
which is waisteful. Instead do this:

foreach(DictionaryEntry de in ht) {
this.setProperty(de.Key, de.Value);
}

You may need some casting depending on how setProperty is declared.

In general you don't want to replace for-each loops with indexed
loops.

HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking Mid/Sr. .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.
On 1 Feb 2007 08:56:45 -0800, "Akira" <ak***@regonline.comwrote:
>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.setProperty( propertyName, ht[propertyName] );
}
Feb 1 '07 #4

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

Similar topics

5
by: John Dumais | last post by:
Hello, I have been trying to figure out how to write an array of doubles (in this specific case) to a binary stream without using a loop. What I have been doing is... foreach(double d in...
6
by: eBob.com | last post by:
How do you make a loop iterate early without using a GoTo? (I guess I've done too much structured programming and I really don't like using GoTos.) Here's my code ... For Each Thing As OFI...
20
by: bubunia2000 | last post by:
Hi all, I heard that strtok is not thread safe. So I want to write a sample program which will tokenize string without using strtok. Can I get a sample source code for the same. For exp:...
1
by: Rejimonb | last post by:
Can I fill a combobox without using a loop. Using a loop will be time consuming. Reji
2
by: Bernard Dhooghe | last post by:
The information center writes: "Encryption Algorithm: The internal encryption algorithm used is RC2 block cipher with padding, the 128-bit secret key is derived from the password using a MD2...
1
khalidbaloch
by: khalidbaloch | last post by:
hi every one, how are you folf , hope fine dear Friends i want to get values of multi-dimensional arrays using foreach loop and after that print out the html using an other while loop , i tried...
94
by: krypto.wizard | last post by:
Last month I appeared for an interview with EA sports and they asked me this question. How would you divide a number by 7 without using division operator ? I did by doing a subtraction and...
13
by: inpuarg | last post by:
Is it possible to get all controls and all of their children on a Windows form without using recursive methods ?
1
by: vit159 | last post by:
I have Data Recive it from stordProceder and i want to Get this data using foreach loop to equal it with local variable
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
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: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.