11

Am using a For Loop like following:

 for (int i = 0; i < 1000; i++)
    {
        int mod = i % 1795;
       //Do some operations here
    }

it works fine, but when i put a break point and apply condition as mod=150 then it slow down the execution. why this is happening? what is actually happening when i add such conditional breakpoints?

enter image description here

sujith karivelil
  • 26,861
  • 6
  • 46
  • 76

1 Answers1

18

A conditional breakpoint is not something supported by the hardware; processors only support unconditional breakpoints. What's going on is that when you create a conditional breakpoint, the debugger inserts an unconditional breakpoint into your code. When the unconditional breakpoint is hit, the debugger evaluates your condition, and if it fails just resumes execution. Since each pass by the breakpoint location now requires stopping and involving the debugger, the code runs much more slowly.

Depending on how often that code executes and how long your code takes to build it's often faster to just add an

if (your condition)
{
    System.Diagnostics.Debugger.Break();
}

or similar and just rebuild your app.

Billy ONeal
  • 97,781
  • 45
  • 291
  • 525
  • "Debugger.Break()" also plays very nicely in combination with Edit and Continue (when available). Then you don't even need to rebuild (at least not immediately). – Antitoon Aug 22 '17 at 14:19
  • The why is a conditional break point literally orders of magnitude slower than an if followed by the break statement? Seriously, try it out, it's ridiculous. – Ed S. Aug 23 '17 at 15:36
  • @EdS. Because stopping your program, having the debugger evaluate the condition, and if false resume your program involves at least a context switch which is far more expensive than a branch in your program's code. – Billy ONeal Aug 24 '17 at 22:15
  • Sorry, I completely misread this: *" the debugger inserts an unconditional breakpoint into your code"*. I guess I also failed to continue reading as I recall thinking you were saying that the debugger was inserting a *conditional* breakpoint, e.g., exactly the same thing as a branch. Don't mind me, must have been a long day... – Ed S. Aug 29 '17 at 16:31