speed about foreach , copy list to an arry then loop

R

Ryan Liu

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
 
J

Jon Skeet [C# MVP]

Ryan said:
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
 
M

Marc Gravell

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<T> does 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 ReaderWriterLock 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top