[Mono-list] Buffering for StreamWriter

Dan Lewis dihlewis@yahoo.co.uk
Thu, 16 May 2002 21:25:57 +0100 (BST)


On Thu, 2002-05-16 at 20:05, Marsh, Drew wrote:
> Actually, foreach does something different than a for loop would. It calls
> IEnumerable::GetEnumerator() and uses the semantics of the IEnumerator
> interface to iterate the items in the container. Whereas for would index
> into the container each time.

Foreach can have some quite complicated semantics - especially in the presence
of disposable collections - but generally it just tells the compiler "enumerate
the elements of this collection or array". There's no requirement to use
GetEnumerator().

Even simple compilers will be able to spot an array enumeration by looking at
the static type of the argument. They would be very lazy to implement a foreach
using Array.GetEnumerator().

Have a go at compiling and disassembling some loops with mcs and csc. I'd be
interested if you could show me a for loop that generated better IL code than
its equivalent foreach. In fact until recently, foreach was 9x faster on an
array compiled with mcs than a for loop!

> Depending on the container, one might be faster than the other.

The beauty of the foreach construct is that you leave the hard work of choosing
the optimum iteration code to the compiler. Writing enumeration code in Java
with for and while now makes me want to cry.

This is what I love about C#. They took Java, looked at the common programming
idioms that were popping up all over the place in peoples code, formalized
them, and made them part of the language. For the developers, it's clearer
code. For the compilers, it's clearer semantics, and a much better shot at
optimization.

For example, there's actually an optimization in the
> The JIT will do away with bounds checking which will obviously result in a
> signifigant performance increase.

Yes. Bounds-check elimination is quite a smart little piece of technology that
definitely boosts performance. Hopefully if Dietmar gets SSA transformation
into the JIT we'll be able to do tricks like this.

The dataflow analysis that the JIT does is pretty much independent of the
constructs used in C# code though.

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.

I'd be very interested if you could duplicate this performance hike on either
MS.NET or Mono.

Dan.


__________________________________________________
Do You Yahoo!?
Everything you'll ever need on one web page
from News and Sport to Email and Music Charts
http://uk.my.yahoo.com