views:

136

answers:

2

Normally I'm well aware that a consideration like this is premature optimization. Right now I have some event handlers being attached inside a foreach loop. I am wondering if this style might be prone to leaks or inefficient memory use due to closures being created. Is there any validity to this thinking?

+1  A: 

closures only apply if your event handlers are anonymous methods (including, but not limited to, lambda expressions). If this is the case, you might have a problem. But it should be okay as long as you remove these event handlers at the proper time.

Joel Coehoorn
If no anonymous methods are used, is there a significant performance difference when using foreach vs for?
ifwdev
The only way to know is to profile, but I'm pretty confident in saying there won't be.
Joel Coehoorn
A: 

If you are talking about something like this:

foreach (var item in items)
{
    item.SomeEvent += delegate {
        // do something
    };
}

Then the answer is the performance is not noticeable (in my Monotouch experience anyway) as the compiler simply creates a class with a method the same way the Microsoft C# compiler.

The biggest performance bottlenecks I've encountered in Monotouch have been SQLite related, and parsing DateTimes. Everything else, including complex LINQ statements fly on the 3GS - I'm not sure what magic is performed by the AOT compiler but I would only worry if it creeps up into 0.5 or more seconds to perform the task.

Chris S