[Mono-list] for vs. foreach

Dan Lewis dihlewis@yahoo.co.uk
Sat, 18 May 2002 14:42:36 +0100 (BST)

 --- Serge <serge@wildwestsoftware.com> wrote:
> 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.

Ok, that's very interesting!

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

I would certainly think so for strings, being immutable. I don't see why the
compiler needs to go to the effort of using a CharEnumerator.

For general collections, I suppose the situation is different. The foreach
operator looks designed specifically to introduce a number of safety features.

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

Thanks Serge and Drew for adding some light on this area. I'm still a big fan
of foreach though.


Do You Yahoo!?
Everything you'll ever need on one web page
from News and Sport to Email and Music Charts