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 checked to make sure that the profiler was running the debug version of my app, and sure enough, it was. Or at least the "DEBUG" symbol was defined, and that's what matters most. I reasoned that even if the profiler was overriding the "disable JIT optimizations" setting, the difference would not be anywhere near 10 times.

I tried the release version just in case, 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.

Hoping that others may have had the same problem before me, I tried my luck with various searches, and I found a couple of articles on StackOverflow, but none pointed at the exact cause of the problem.

Luckily, after a bit of hard thinking, I found the answer: it is the "Enable unmanaged code debugging" flag, which in Visual Studio is not under "Tools / Options / Debugging", (that would make too much sense,) it is under "Project / Properties / Debug". Checking that checkbox simply makes the debugger slow as molasses. The profiler disables the debugger, so the application appears to run lightning fast.

Here are two related StackOverflow questions to which I added my newly acquired wisdom: