Since it’s Friday, I figured it’s time for another debugging tale. This weeks installment: How to have conditional breakpoints in Visual Studio that don’t cost an arm and a leg in performance – and stick around in optimized builds.
While VS.NET does offer you conditional breakpoints, it does so by evaluating an expression every single time that breakpoint gets hit. Clearly, that’s not acceptable – especially if the breakpoint is hit often and the condition is rarely true.
You can speed this up quite a bit by moving the condition into actual (compiled) code. For that, you need a line of code that is only reached when the condition is true. I.e.
if(condition) {
DoSomethingWithoutConsequences();
}
A breakpoint there will only be triggered if the condition is true, and the condition is evaluated in compiled code – just what we want.
The only drawback is that doing something without consequences gets ripped out by the optimizer ruthlessly. Which causes the if() statement to be removed too, and our whole scheme collapses. The most widely known way to work around this is incrementing a volatile global – but that adds even more code to type, and we can’t do it as a simple paste operation in a single place.
Thankfully, there’s an easy solution to this – the optimizer never touches inline assembly. So turn the above into:
if(condition) {
__asm{ nop };
}
Then, in the debugger, put a real breakpoint on the assembly instruction, and you’re good to go.