Different C# Output Between Release and Debug

陌路散爱 提交于 2019-12-05 20:48:58

The static class initializer is not called until its needed. Clearly the debug and release versions decided differently about when its needed. IN particular my guess is that the release build optimized the main out entirely and so never loaded the class. It seems to have decided that since main does nothing it can optimize everything out - in this case it seems to be a bad decision

Blorgbeard

Turning optimizations on (release mode) affects the IL generated, as well as the behaviour of the JITter.

You are probably seeing the initialization of the unused variables being eliminated by the JITter.

This explains the ILDASM/ILASM behaviour, and the fact that there's no significant difference in the IL.

I suspect this behaviour is controlled by the value of the CorDebugJITCompilerFlags flag somewhere in the CLR header.. See Does C# compiler /optimize command line option affect JITter?

After more research, I found the answer I was looking for (thanks to Blogbeard for pointing me in the right direction).

It turns out that when you compile for Debug, the generated assembly is, by default, decorated with a DebuggableAttribute whose "Debugging Mode" is

DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.Default

It is apparently this combination of flags that seem to turn off JIT optimization, resulting in the output I saw in the Debug version of the program. The Release version of the program has a different "Debugging Mode", allowing JIT optimization to proceed.

Of course, if you manually set the DebuggableAttribute in the AssemblyInfo (as I did during testing) for the Debug build, you can override the default behavior.

I'm sure there are some CLR/JIT Lawyers out there who can explain in greater detail.

You don't actually use the variables a, b, or c in the application (inside Main) anywhere so I'm assuming they're being optimized away. When I run that code in LinqPad with optimizations off, it shows the output you describe and with optimizations on, it shows nothing other than Main() executing. If I update the code in Main() to reference one of those variables, the output is consistent with the optimizations off build.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!