2012-04-27

.Net code running faster under the profiler?

So, today it occurred to me that the C# application that I am developing is a bit too slow on startup, and I decided to throw the visual studio profiler at it to see if I have goofed up somewhere. To my astonishment, under the profiler my app ran 10 times faster. The slowness I wanted to troubleshoot was nowhere to be found.

I also tried running the release version, and as I expected it performed better than the debug version under the profiler, so the universe was still in its place, but still, I would very much like to know what the profiler did that made the debug version of my app run so much faster. For one thing, it would be a great convenience to be able to enjoy this speedup while developing; waiting for 2 instead of 20 seconds for my app to start every time I want to check something would be very good for productivity.

I tried my luck with various google searches, and I found a couple of articles on StackOverflow, but none pointed at the exact cause of the problem.

Luckily, after quite a bit of hard thinking, troubleshooting, and browsing through the myriad of potentially relevant settings in Visual Studio, I found the answer: 

It is the "Enable unmanaged code debugging" feature.

In Visual Studio this feature is not under "Tools / Options / Debugging", (because that would make too much sense,) it is under "Project / Properties / Debug".  Enabling that feature makes everything slow as molasses. The profiler disables the debugger, and that feature with it, so the application appears to run lightning fast.

Here is a StackOverflow question to which I added my newly acquired wisdom:

stackoverflow.com: Launching VS Profiler boosts Application Performance x20?