Is there any overhead in the use of anonymous methods?

后端 未结 8 1742
遇见更好的自我
遇见更好的自我 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:54

    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.

    0 讨论(0)
  • 2021-02-15 18:00

    My concern has always been - using delegates in a loop. Turns out the compiler is smart enough to cache anonymous functions even when used in a loop.

    Here's my code (10 million iterations):

    var dummyVar = 0;
    var sw = new Stopwatch();
    
    //delegate inside loop
    sw.Start();
    for(int i=0; i<10000000; i++)
    {
        Func<int, int> ax = delegate (int x) { return x++; };
        dummyVar = ax(i);
    }
    sw.Stop();
    var ms = sw.ElapsedMilliseconds;
    
    //delegate outside loop
    Func<int, int> ax2 = delegate (int x) { return x++; };
    sw.Restart();
    for (int i = 0; i < 10000000; i++)
    {
        dummyVar = ax2(i);
    }
    sw.Stop();
    var ms2 = sw.ElapsedMilliseconds;
    

    Results:

    1st: 151 milliseconds

    2nd: 148 milliseconds

    2nd run

    1st: 149 milliseconds

    2nd: 175 milliseconds (SLOWER this time... who knew)

    0 讨论(0)
提交回复
热议问题