[Mono-list] foreach issues

Ben Maurer bmaurer@users.sourceforge.net
Sat, 10 Apr 2004 10:42:31 -0400


On Sat, 2004-04-10 at 04:18, Pedro Santos wrote:
> Hi, I was wondering what would be faster when using foreach: an
> ArrayList ou an Array.
On an array will be faster -- much faster.

> But, doesn't foreach see the Array and the ArrayList has a IEnumerable?
> Whouldnt it be the same in the foreach prespective?
On an array, MCS generates code that behaves exactly as:

for (int tmp = 0; tmp < array.Length; tmp ++) {
	object o = array [tmp];
	<foreach body>
}

On an IEnumerable, MCS generates code exactly like:

IEnumerator enumerator =
((System.IEnumerable)(collection)).GetEnumerator();
try {
   while (enumerator.MoveNext()) {
      ElementType element = (ElementType)enumerator.Current;
      statement;
   }
}
finally {
   IDisposable disposable = enumerator as System.IDisposable;
   if (disposable != null) disposable.Dispose();
}

Now, note that any Array is IEnumerable. If you cast it to that
interface, we must generate the `slow' code.


I have been thinking about writing an article about foreach performance,
so checkout monologue every once in a while.

-- Ben