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<Tdoes 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