views:

74

answers:

3

Rather, is there a way to tell if it's been compiled with the optimization parameter enabled or disabled. I don't want to know if it's release or debug, since either can be enabled with or without optimizations. From my perspective, even though the code says it's release version, is it truly optimized? Thanks.

+1  A: 

This post might help you http://www.panopticoncentral.net/archive/2004/02/03/267.aspx

Specifically, in ildasm, you could look for the DebuggableAttribute and the absence of NOPs.

Zaki
@Zaki, that info is specific to the VB.Net compiler. It has very similar but slightly different semantics than C#.
JaredPar
+2  A: 

One way to check is to look at the DebuggableAttribute (doc) on the assembly. The DisableOptimizations flag will not be set if the C# complier was passed the /optimize option.

Note: Although this will work for the majority of scenarios this is not a 100% fool proof solution. It can be broken it at least the following ways

  1. Compiling with another language that has different semantics for optimization
  2. If the user hand defines the DebuggableAttribute it will take precedence over what the C# compiler defines
JaredPar
1. is probably not a problem, as the question was about C# assemblies, however, wouldn't 2. be still valid (if the user overrides the attribute, wouldn't that get rid of the runtime optimizations and thus the assembly could be thought of as not optimized?)
Zaki
@Zaki yes and no. JIT optimizations would be disabled but other C# compiler optimizations would not be enabled.
JaredPar
/optimize == /optimize-
Hans Passant
@Hans, thanks updated to /optimize+.
JaredPar
That's backwards, isn't it?
Hans Passant
@Hans, confused myself with the negatives. Fixed.
JaredPar
Sweet, thanks folks. Found this on Scott Hanselman's blog giving code to do just that. Thanks.http://www.hanselman.com/blog/HowToProgrammaticallyDetectIfAnAssemblyIsCompiledInDebugOrReleaseMode.aspx
John
+2  A: 

Look at the assembly manifest with Ildasm.exe:

  // --- The following custom attribute is added automatically, do not uncomment -------
  //  .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(
          valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) 
          = ( 01 00 02 00 00 00 00 00 ) 

That's the Release version. The debug build values are ( 01 00 07 01 00 00 00 00 )

Yet another wrinkle is that the debugger can disable the JIT optimizer. That's a configurable option in VS, Tools + Options, Debugging, General, "Suppress JIT optimization on module load". You want that off if you're debugging the Release build and want comparable perf. It makes debugging more challenging, stepping acts weird as the optimizer rearranges and inlines code and you often cannot inspect the values of local variables because they are stored in CPU registers.

Hans Passant