What does “Optimize Code” option really do in Visual Studio?

前端 未结 3 2072
礼貌的吻别
礼貌的吻别 2020-11-28 05:04

Name of the option tells something but what Visual Studio/compiler really do and what are the real consequences?

Edit: If you search google you can find this address

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 05:33

    From Paul Vick's blog:

    • It removes any NOP instructions that we would otherwise emit to assist in debugging. When optimizations are off (and debugging information is turned on), the compiler will emit NOP instructions for lines that don't have any actual IL associated with them but which you might want to put a breakpoint on. The most common example of something like this would be the “End If“ of an “If” statement - there's no actual IL emitted for an End If, so we don't emit a NOP the debugger won't let you set a breakpoint on it. Turning on optimizations forces the compiler not to emit the NOPs.

    • We do a simple basic block analysis of the generated IL to remove any dead code blocks. That is, we break apart each method into blocks of IL separated by branch instructions. By doing a quick analysis of how the blocks interrelate, we can identify any blocks that have no branches into them. Thus, we can figure out code blocks that will never be executed and can be omitted, making the assembly slightly smaller. We also do some minor branch optimizations at this point as well - for example, if you GoTo another GoTo statement, we just optimize the first GoTo to jump to the second GoTo's target.

    • We emit a DebuggableAttribute with IsJITOptimizerDisabled set to False. Basically, this allows the run-time JIT to optimize the code how it sees fit, including reordering and inlining code. This will produce more efficient and smaller code, but it means that trying to debug the code can be very challenging (as anyone who's tried it will tell you). The actual list of what the JIT optimizations are is something that I don't know - maybe someone like Chris Brumme will chime in at some point on this. The long and the short of it is that the optimization switch enables optimizations that might make setting breakpoints and stepping through your code harder.

提交回复
热议问题