Is there any overhead in the use of anonymous methods?

后端 未结 8 1764
遇见更好的自我
遇见更好的自我 2021-02-15 17:27

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 S         


        
8条回答
  •  不知归路
    2021-02-15 17:52

    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.

提交回复
热议问题