0

Apologies for the unhelpful title, I'm not sure I actually understand that what I'm asking is happening. I know embarrassingly little about what the CLR and JIT does or how to check that it's doing what I think it should be doing.

Let's say I have the following method:

void DoSomething(bool log) {
   for (int i=0; i< 1000000; i++) {
      if (log) {
          Console.WriteLine(i);
      }
      Console.WriteLine(i*2);
   }
}

Now, if my method call is DoSomething(false), will the CLR/JIT know to not check if (log) 100,000 times? Basically, will it automatically convert it to:

void DoSomething_noLog() {
    for (int i=0; i< 1000000; i++) {
        Console.WriteLine(i*2);
      }
}

If it does know to do this automatically, how can I verify that it really is doing this?

Matt
  • 25,943
  • 66
  • 198
  • 303
  • It is not real code so a concrete answer is not useful. But yes, it can happen when the method gets *inlined* and the code optimizer can tell in the calling method that *log* is always false. That's not terribly likely to happen since *log* would typically be configuration. Inlining and dead code elimination are described [here](https://stackoverflow.com/a/4045073/17034). – Hans Passant Mar 18 '20 at 22:27
  • 1
    To verify, use Tools > Options > Debugging > General, untick "Suppress JIT optimization". Switch to the Release build, set a breakpoint in the caller method and when it hits use Debug > Windows > Disassembly. – Hans Passant Mar 18 '20 at 22:31

0 Answers0