Is there a way to tell if a C# assembly has been compiled with the optimization parameter?
Rather, is there a way to tell if it's been compiled with the optimization parameter enabled or disabled. I don't want to开发者_如何学C 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.
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
- Compiling with another language that has different semantics for optimization
- If the user hand defines the
DebuggableAttribute
it will take precedence over what the C# compiler defines
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.
I'm 8 years late but if you, like me, wanted a C# way, here it is:
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
internal static class AssemblyExtensions
{
public static bool IsOptimized(this Assembly asm)
{
var att = asm.GetCustomAttribute<DebuggableAttribute>();
return att == null || att.IsJITOptimizerDisabled == false;
}
}
As an extension method:
static void Main(string[] args)
{
Console.WriteLine("Is optmized: " + typeof(Program).Assembly.IsOptimized());
}
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.
精彩评论