Wednesday, November 10, 2004

[C#] iterating through collections

I Googled this today - it explained nicely a problem I was having, and got me to start thinking about the differences between a loop that reads:
MyObject obj = null;
for (int i = 0; i < someCounter; i++)
{
    obj = MyObjectCollection[i];
    obj.Foo();
}
as opposed to this:
foreach(MyObject o in MyObjectCollection)
{
    o.Foo();
}
I'd always suspected that there were likely overhead/performance problems with the foreach/in statement, but damn is it convenient. I'd never suspected that the loop used a fundamentally different mechanism to achieve that ease of use. What I found interesting is that while the author of the referenced blog entry took home the lesson that 'mutable value types' == potentially harmful, the lesson I got was 'foreach/in' == potentially harmful. I agree that structs that act more like classes should probably be classes - on the other hand, if you can't predict what is going to come out of a statement shouldn't that be viewed as the problem? (And I'm going to have to find an addition to my css in order to format code snippets better...) [Update 11/12/2004: found it! Right here; prettified the code, though I'm not too sure about the absolutely stark-white background. It'll stay that way for now]

0 Comments:

Links to this post:

Create a Link

<< Home