0

I am compiling a C# program through csc.exe.

I've noticed that default setting for csc.exe is to not include the optimize option. Instead you have to explicitly state it with the /optimize flag.

I would like to know if there are any potential adverse impacts to using the /optimize flag. In other words, why wouldn't I always want to use it?

I am interested in understanding exactly what the flag does "under the hood", so any link to some good documentation would be appreciated (haven't found anything on MSDN or Google yet).

Thanks

datalinked
  • 13
  • 3
  • 1
    Perhaps you can imagine that you are not the first C# programmer that wondered about this option. Google "c# compiler /optimize option" and the first 6 hits include 4 SO questions that already asked this. – Hans Passant May 06 '14 at 12:37
  • @HansPassant - I probably could have done a better job with my search. Perhaps I was too focused on csc.exe as I was using the search term "csc.exe /optimize" and it did not return any good results. Thank you for the link to the prior post. I found the link to Eric Lippert's post particularly informative [link](http://blogs.msdn.com/b/ericlippert/archive/2009/06/11/what-does-the-optimize-switch-do.aspx) – datalinked May 06 '14 at 13:29

1 Answers1

3

The best documentation you will find is the code of the new compiler platform 'Roslyn' you can follow the compiler flag from CompilationOptions.cs

public bool Optimize { get; protected set; }

If you click on the property you will see all references in the code.

One of the main consequences of this flag seem to be that Optimizer.Optimize is called and try to optimize the code, especially to reduce pushing things on the stack as much as possible.

var a = Foo();
var b = Bar();
Baz(a, b);

Can be written as (pseudo-IL):

Declare Locals a, b
Call Foo
a := pop stack
Call Bar
b := pop stack
push a
push b
Call Baz

But that's totally possible to optimize it to remove locals:

Call Foo
Call Bar
Call Baz

(There are obviously more complex cases)

Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
  • @virtualblackfox- Thank you for the link to the Roslyn source code. That really helps me to understand what's going on behind the scenes. I appreciate the example you provided as well to help understand what types of optimizations the option attempts to make. – datalinked May 06 '14 at 13:42