[Mono-list] for vs. foreach

Serge serge@wildwestsoftware.com
Sat, 18 May 2002 16:19:47 +0300

Out of curiosity I decided to check whether hand-coded for-loop is faster
than foreach (at least for strings as it was suggested).
Here is some sample code:

For-loop (or more precisely, code generated by MCS or CSC) for strings
is indeed 2-7 times faster under .NET (results may vary between runs),
and roughly two times faster under Mono.
With Collections speed difference is not that big but still exists
(usually 'for' is 2 times faster in simple tests).

More general question: Is it correct to optimize Enumerators away when
generating foreach code? For example using Item accessor and a for-like loop.
In other words producing code that is as fast as hand-coded for-loop.
It seems that when using foreach (as opposed to hand-coded for-loop) one may
expect fail-fast behaviour in the case of concurrent modification -
this won't happen if foreach will be replaced with compiler-generated for-loop.

Anyhow, it seems that code generated by foreach is quite different from for-code
in most cases (strings, collections). And hand-coded 'for' is indeed faster in those cases.
Is this correct? Am I missing something?