Igor Ševo
Igor Ševo

Reputation: 5515

Performance diagnostics improves performance

I have run into a strange anomaly within Visual Studio 2013. I am running performance analysis on my program (using CPU sampling) and I found that, in certain scenarios, the program runs faster while being analyzed. The performance analysis seems to improve the performance of the program in cases where it needs to work with smaller amounts of data. The program is parallelized using parallel extensions (C# and LINQ).

My assumption is that this has something to do with parallelism and small amount of data.

Has anyone had this happen or can anyone explain what could be the cause?

Upvotes: 1

Views: 84

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127563

When you run the profiler the debugger will not be attached. Having the debugger attached prevents a LOT of optimizations from happening when you run your program, this mainly is because you would loose information that you may want to know during the debugging process.

Here is a simple example.

void SomeFunction()
{
    var foo = new SomeTypeThatTakesUp1GBOfRam();

    DoSomthingWithFoo(foo);

    for(int i = 0; i < 10000; i++)
    {
        Thread.Sleep(1000);
    }
}

When you have the debugger attached foo can not be garbage collected until it goes out of scope at the bottom of the function (which will take quite some time). If you did not have the debugger attached foo would be eligible for garbage collection as soon as DoSomthingWithFoo(foo) returns.

The reason it has to wait to collect it is what if you paused the debugger on the 2000th loop of the for loop and wanted to see the value of foo? You can only do that if the garbage collector has not collected the variable yet. If the debugger is not attached the runtime knows that nothing is going to "need to see" foo at any later point in time so it gets rid of it.

Upvotes: 3

Related Questions