I would expect foreach to work nominally faster in some cases, and about the same in others, except when the elements are an actual array, in which case the performance difference is not significant.
If implemented on top of a counter, it may be more efficient than direct indexing, depending on the implementation. This is unlikely to be less effective. For example, if someone put up a balanced tree, both indexed and enumerable, then foreach will be decently faster. This is due to the fact that each index will have to find the reference element on its own, while the enumerator has the context of the current node in order to more effectively move to the next ont.
If you have an actual array, it depends on the implementation of the language and class, whether foreach will be faster for the same as for.
If indexing is a literal memory offset (e.g. C ++), then this should be a little faster, since you avoid calling the function. If indexing is indirect, like a challenge, then it should be the same.
All that has been said ... It is difficult for me to find here a case of generalization. This is the last kind of optimization you should look for, even if your application has performance issues. If you have a performance problem that can be solved by changing the way you repeat, you really have no performance problem. You have a BUG because someone wrote either a very crappy iterator or a really crappy index.
Darren Clark Apr 21 '09 at 4:50 2009-04-21 04:50
source share