473,618 Members | 3,044 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

speed about foreach , copy list to an arry then loop

Hi,

I heard foreach is slower then use loop directly, is that really true?

When loop though a list in a multiple thread environment, is that a good
practice to copy this list to an array the loop though it?

Thanks,
Ryan Liu
Aug 22 '06 #1
2 3365
Ryan Liu wrote:
I heard foreach is slower then use loop directly, is that really true?
It depends on *exactly* which type is involved. foreach uses an
iterator, which in some cases will be faster than an indexer, and in
some cases will be slower. It's almost never a significant part of
performance though.
When loop though a list in a multiple thread environment, is that a good
practice to copy this list to an array the loop though it?
Not if all threads are just reading from the list.

Jon

Aug 22 '06 #2
A common question; simply: it depends on the collection! For simple arrays,
for instance, I believe the indexer usage is marginally faster - however,
the difference is very small. For more complex objects you should generally
assume that the iterator (foreach) knows what it is doing and is a good way
to iterate through the data. As an example, for a linked-list, there can
(depending on implementation) be a huge difference between indexer access
and iterator access - the iterator being O(n), and indexer O(n^2) - i.e.
*hugely* faster to use the iterator. And IIRC LinkedList<Tdoe s not provide
an indexer - I'm talking about the concept, not any specific implementation.

Also bear in mind that IEnumerable[<T>] only supports foreach (not indexer).
foreach is a good way of coding; unless you have real numbers pointing to
this as a performance issue, I'd stick with it.

In the threaded environment, it depends on what the threads are doing. If
all threads are reading, then fine; use concurrent iterators. If you have a
mixture of reader(s) and writer(s) then you neeed to start thinking about
locking. I tend to avoid ReaderWriterLoc k as overkill, so yes, in this
situation (and if you intend doing non-trivial work for each item), it may
be prudent to: lock the collection; copy to an array; unlock; enumerate the
array. Assuming the other threads also lock for their critical access this
should keep things happy. Even then, I'd need to pinpoint this as a
bottleneck first, otherwise it may be a premature optimisation.

Marc
Aug 22 '06 #3

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

Similar topics

8
2975
by: Rob Ristroph | last post by:
I have tried out PHP 5 for the first time (with assistance from this group -- thanks!). The people I was working with have a site that uses lots of php objects. They are having problems with speed. They had a vague idea that PHP5 has improved handling of objects over PHP4, so it would probably be faster also. In fact it seems slower. We did a few timing loops, in which a a number of objects were created and and members were...
32
4126
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open Source" manner, and in an attempt to build a ground-swell of support to convince the folks at Microsoft to add it. Proposal: "first:" "last:" sections in a "foreach" block The problem: The foreach statement allows iterating over all the...
104
7137
by: cody | last post by:
What about an enhancement of foreach loops which allows a syntax like that: foeach(int i in 1..10) { } // forward foeach(int i in 99..2) { } // backwards foeach(char c in 'a'..'z') { } // chars foeach(Color c in Red..Blue) { } // using enums It should work with all integral datatypes. Maybe we can step a bit further: foeach(int i in 1..10, 30..100) { } // from 1 to 10 and 30 to hundred
4
2560
by: Sjoerd | last post by:
Summary: Use foreach(..) instead of while(list(..)=each(..)). --==-- Foreach is a language construct, meant for looping through arrays. There are two syntaxes; the second is a minor but useful extension of the first: foreach (array_expression as $value) statement
12
8346
by: mart.franklin | last post by:
I hope I am not being too ignorant :p but here goes... my boss has written a bit of python code and asked me to speed it up for him... I've reduced the run time from around 20 minutes to 13 (not bad I think ;) to speed it up further I asked him to replace a loop like this:- index = 0 for element in a: av = a
2
2347
by: The.Relinator | last post by:
Hello, I am unable to get the following piece of code to work as desired. The fields valuable seems to contain all values however the vaules variable only contains the first assignied with $values = '\'' . $arry] . '\''; Any help regarding this issue would be kindly appreciated, thank you. $keys = array_keys($arry); $fields = '`' . $keys . '`'; $values = '\'' . $arry] . '\''; foreach($keys as $key)
3
33350
by: Akira | last post by:
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 );
29
4221
by: Jon Slaughter | last post by:
Is it safe to remove elements from an array that foreach is working on? (normally this is not the case but not sure in php) If so is there an efficient way to handle it? (I could add the indexes to a temp array and delete afterwards if necessary but since I'm actually working in a nested situation this could get a little messy. I guess I could set there values to null and remove them afterwards? Thanks, Jon
10
2934
by: fig000 | last post by:
HI, I'm new to generics. I've written a simple class to which I'm passing a generic list. I'm able to pass the list and even pass the type of the list so I can use it to traverse it. It's a generic list of business objects. I'm able to see that the type is the correct one in the debugger. However when I try to traverse the list using the type I can't compile. The same type variable I've verified as being passed
0
8212
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
8653
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
8595
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8304
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8455
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
5552
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4065
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4150
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1459
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.