Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I NOT use the /optimize switch to compile my C# code?

In Visual Studio 2008 there is an option "Optimize Code" that probably corresponds to the /optimize option. It is never enabled, not even when in "Release" mode.

Why should I not want this option to be enabled at all times?

like image 917
Boris Callens Avatar asked Jan 23 '09 11:01

Boris Callens


People also ask

Why is optimization attempted by a compiler but not by an assembler?

In any case optimization is done by compiler, which is language-dependant, not by the assembler. No because one instruction in assembly corresponds to one instruction in machine code.

Can human being optimize a program better than an automated compiler?

So, with the same degree of knowledge, humans can produce assembly code that is at least as performant as the compilation result. It can probably be even better, as a human developer can optimize for a given task, while the compiler can only apply generic optimizations.

Why is optimization significant phase in compilation?

Code optimization is an important phase to improve the time and space requirement of the generated target code. Given a code in intermediate form it applies optimizing techniques and reduces the code size and returns the code in intermediate form.


3 Answers

It is on per default for release builds (perhaps you changed the settings for Release builds?). Turn it off to make debugging easier. For release code, turn it on.

like image 153
Brian Rasmussen Avatar answered Sep 28 '22 06:09

Brian Rasmussen


Code optimisation has gotten pretty good in C#3 - it does lots of clever performance tweaks that change your code quite a lot more in the IL than you might expect.

Some obfuscation tools (and some other IL tools like ILMerge) can sometimes break the assembly with optimisation on. The more IL tools you use the more likely you are to get serious issues with optimisation.

Also as @Brian Rasmussen already said (+1) - you want it off for debugging, on for releases.

like image 40
Keith Avatar answered Sep 28 '22 06:09

Keith


To make this clear, optimization does inline functions and eliminate some variables. When debugging optimized code, you won't get as much help by the IDE as usual, since some of the code actually does not exist anymore. So for debugging, turn if off (default).

In languages like C++ optimization sometimes (often) has critical side effect that need to be considered. As far as i know, this is not or almost not the case for C#, so from the point of correctness of your code, it probably does not matter if you optimize or not.

like image 40
mafu Avatar answered Sep 28 '22 06:09

mafu