473,748 Members | 2,211 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Feb 1 '07 #1
3 33369
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.setPropert y( 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.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
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(Diction aryEntry de in ht) {
this.setPropert y(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***@regonlin e.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.setPropert y( 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
5992
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 TraceData) { instanceOfBinaryWriter.Write(d); }
6
3651
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 In FileInfo If Thing.Displayed <> True Then GoTo Iterate 'skip this entry; try next one End If
20
17241
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: 0.0.0.0--->I want to tokenize the string using delimiter as as dot. Regards
1
1739
by: Rejimonb | last post by:
Can I fill a combobox without using a loop. Using a loop will be time consuming. Reji
2
7691
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 message digest. " and also explains how the length of the encrypted column can be derived.
1
4337
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 alot but did not successed accutly i want to create an yahoo api websearch application i got a sample from developer.yahoo.com for this purpose ,this sample uses unserialize/serialize php here is the code exapmle <?php // Parsing Yahoo! REST...
94
11503
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 keeping a counter that kept a tab on how many times I subtracted. Later, the EA sport guy told me that of course there are can be better technique by using bit operator.
13
12988
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
1561
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
8991
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8831
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9552
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9249
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8245
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.