FW: [Mono-list] Buffering for StreamWriter

Miguel de Icaza miguel@ximian.com
18 May 2002 00:49:23 -0400

> In the future it's been said that the C# compiler itself will detect a
> foreach on an array and instead emit a for loop in IL so that users don't
> need to know about this little JIT optimization trick.

Actually, that has been in .NET ever since I recall (you can check the
code generated by foreach for single-dimension arrays and
multiple-dimension arrays as well as IEnumerables).  The Mono C#
compiler implements all the semantics of foreach.

Indeed, when foreach can be used, it will always generate code which is
as good or better than the equivalent for code.

> The JIT will do away with bounds checking which will obviously result in a
> signifigant performance increase. Gunnerson claims 5x faster than foreach in
> his example[1]. It's all about the explicit use of .Length in the
> conditional of the for statement.

Yeah, bound checking elimination is a common compiler optimization.  The
Intel ORP Java JIT engine is a great source of ideas and inspiration for
anyone interested in the topic of JITs.

There is no extra metadata generated for foreach loops, so JITers have
to discover by themselves this invariant from the IL representation.

Btw, the same trick for strings is implemented by the Mono C# compiler,
look in mcs/mcs/statement.cs and scan for 'class Foreach' to see the
implementation: foreach turns out to be six or seven different beasts
depending on its arguments.