Why not always use Optimize Code?

Asked

Viewed 343 times

3

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

Why can’t I always use this option in my projects?

4 answers

6


The option Optimize Code is enabled by default when you perform the build in release mode. The optimizations performed by the compiler may end up hindering the debug while you are developing, this is because compiled code is reorganized for better efficiency, and the result of this can impact directly on Debugger, which cannot identify which source code belongs to a specific set of compiled instructions.

Excerpt from the MSDN

When the Compiler optimizes code, it repositions and reorganizes Instructions. This Results in more Efficient Compiled code. Because of this Rearrangement, the Debugger cannot 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, which is the scenario 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 must debug the Optimized code.

References

3

Because these optimizations are not always desirable. They do not always produce what is expected. Each case is a case and you should choose to call or not after testing both. In addition, it is possible that some type of optimization may make the code incompatible with third-party codes (rare). Most of them don’t generate such expressive gains. Most applications won’t notice when optimization is on or off.

Can disturb in particular debugging, but not only.

Outdated list of optimizations.

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

  • 2

    They are enabled by default for release by Visual Studio, not by the compiler.

2

Serves to compile 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 memorize the method using the attribute [MethodImpl(MethodImplOptions.NoOptimization)] in the method.

Example:

[MethodImpl(MethodImplOptions.NoOptimization)]
private void CallMethodsWithOptimizationDisabled()
{
    //método compilado sem otimização
}

2

Because the code is changed somehow automatically, even if in theory it doesn’t change much.

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

I’ve also seen optimization bugs in the compiler get in the way of the end result, but I’ve never seen a C# problem related to that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.