Home | Shorter Path | About Me
Home
About Me

Archive

2004

01

02

03

04

05

06

07

08

09

10

11

12

 

2005

01

02

03

04

05

06

07

08

09

10

11

12

 

2006

01

02

03

04

05

06

07

08

09

10

11

12


Foreach

Tuesday, May 04, 2004 11:48 PM

Nick Hodges, my TeamB colleague and a confessed Delphi-zealot, just found out that the C# compiler actually converts foreach constructs on arrays to for statements. Microsoft's Brad Adams covered this in a recent post. If you're keeping score, Nick, you'd love this: sometimes, foreach is slower than for.

The performance difference, however, is negligible. The important point is that foreach isn't "syntactical sugar" - it has a definite purpose in life. If all you want to do is iterate through an entire array, then foreach is syntactically identical to for (and therefore generates the same IL). Other cases are not so simple. Foreach and for loops are not identical, as Raymond Chen demonstrates. And, in my opinion, foreach is far more convenient when used on types other than arrays, providing direct access to IEnumerable interfaces.

By the way: I'm moving this blog to a new host, so this page may down be until the DNS changes kick in. If you can't read this, that's the reason.

Copyright 2004 Yorai Aminov