Is there any overhead in the use of anonymous methods?

后端 未结 8 1765
遇见更好的自我
遇见更好的自我 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 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 ax = delegate (int x) { return x++; };
        dummyVar = ax(i);
    }
    sw.Stop();
    var ms = sw.ElapsedMilliseconds;
    
    //delegate outside loop
    Func 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)

提交回复
热议问题