Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any overhead in the use of anonymous methods?

I would like to know if there is any overhead incurred through the use of anonymous methods when creating a Background worker.

for example:

public void SomeMethod()
{
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (sender, e) =>
    {
        //large amount of code
    }

    worker.RunWorkerAsync();
}

Would the example above be any better or worse than defining the //large amount of code in a separate method?

Is there any overhead incurred in defining the background worker method in-line, particularly if SomeMethod() is called often?

like image 307
Lewray Avatar asked Feb 22 '12 12:02

Lewray


2 Answers

There is a small difference in how named methods and anonumous methods are handled when you create a delegate from them.

Delegates for anonymous methods are cached, so there is a small overhead for checking if the delegate already exists in the cache. On the other hand, if you run the method more than once, it will reuse the cached delegate instead of creating a new one.

Delegates for named methods are not cached, so it will be created each time.

Other than that there is no difference. The anonumous method will be created at compile time and exists in the code just like a regular method, only with a name that only the compiler knows about.

like image 187
Guffa Avatar answered Oct 21 '22 03:10

Guffa


First, you probably shouldn't put a lot of code into an anonymous method. It would be more readable if you create a separate method for that, or even better, several methods.

As for the IL generated, if the lambda doesn't close over any variables, then the generated IL code is the same as if you put the code in normal named method (except that the generated method has an unspeakable name).

On the other hand, if you do close over some variable, the compiler creates a closure class to hold that variable in a field. And field access is slightly more expensive that local variable access.

To sum up, if you close over some variables, there is small overhead (including more objects that need to be garbage collected). In most situations, this doesn't matter and worrying about this would be premature optimization. But if you think it does matter, you should profile the code.

like image 22
svick Avatar answered Oct 21 '22 03:10

svick