Cory, while talking about VB compilation options, asks “what exactly can one expect to gain by enabling optimizations?” It’s a good question, and one that the docs are kind of vauge about. Turning on optimizations, which is the default for release builds, does three major things at the compiler level:
- 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. They’re all low-level optimizations, so they’re really applicable to pretty much every kind of application in existence. They’re all also very incremental optimizations, which means that the benefit of any one optimization is likely to be nearly unmeasurable except in the most degenerate cases but in aggregate can be quite significant. I definitely recommend everyone leave this option on for your release build…