Why not always use Optimize Code?

Posted on

Question :

In Visual Studio there is the Optimize Code that has the function of creating optimizations performed by the compiler to make your output file smaller, faster and more efficient.

Why can not I always use this option in my projects?


Answer :

The Optimize Code option is enabled by default when you perform build in release mode . Optimizations made by the compiler can make debug difficult while you are developing, because compiled code is rearranged for better efficiency, and the result of this can directly impact the debugger , which can not identify that a given source code belongs to a specific set of compiled instructions.

MSDN excerpt


When the compiler optimizes code, it repositions and reorganizes
  instructions. This results in more efficient compiled code. Because of
  this rearrangement, the debugger can not always identify the source
  code that corresponds to a set of instructions.

According to the MSDN article, a bug may appear only in the compiler-optimized version, where you should debug the optimized code to find the cause of the problem.


a bug might appear only in an optimized version of a program. In that
  case, you should debug the optimized code.


Because the code is changed somehow automatically, even if in theory it does not change much.

If all goes well, it only disrupts debug (since the code may no longer match the binary) and should take longer to compile, since it has to optimize (the difference may be minimal).

I’ve also seen compiler optimization bugs disrupt the final result, but I’ve never seen a problem in C # related to this.


Because these optimizations are not always desirable. It does not always produce what is expected. Each case is a case and you should choose to call or not after testing both. Also it is possible that some kind of optimization may make the code incompatible with third-party codes (rare). Most of them do not generate such significant gains. Most applications will not notice when optimization is on or not.

It may disrupt debugging, but not only.

Outdated list of optimizations .

According to the documentation optimizations are disabled by default . And I’ve never seen any official information saying otherwise.


It serves to compile the code more efficiently.

But there are cases (pinvoke for example) where optimized code does not work properly, so you can disable optimization in some methods. Just decorate the method using the [MethodImpl(MethodImplOptions.NoOptimization)] attribute in the method.


private void CallMethodsWithOptimizationDisabled()
    //método compilado sem otimização


Leave a Reply

Your email address will not be published. Required fields are marked *