简体   繁体   中英

What runtime optimizations does the /optimize flag enable?

I've long been under the impression that the C# compiler's /optimize flag doesn't do very much. Articles like this one describe how relatively few optimizations are done in IL: most are relegated to the JIT.

However, recently I was trying to speed up some CPU-intensive code (think lots of iterating over arrays and dictionaries as well as well as simple numerics) and I tried turning on optimization just for kicks. The result was a 3x improvement in speed. Note that this was purely from clicking the "optimize" checkbox in the VS project properties page. Toggling the DEBUG and TRACE constants had no performance impact.

While it's entirely possible that the small IL optimizations could have resulted in this change, that seemed pretty surprising to me. Reading up on optimization, I found this tidbit in the MSDN docs :

/optimize also tells the common language runtime to optimize code at runtime.

I'm very curious as to what this means. Does this mean the JIT does NO optimization of code in non-optimized assemblies? What kinds of optimizations does this enable?

Turning on the "Optimize code" option in the project's Build tab does two things. It passes the /optimize+ option to the C# compiler, it performs the minor MSIL optimizations you already know about. But it also gets the C# compiler to emit the [DebuggableAttribute] attribute in the metadata. And you'll get DebuggableAttribute.IsJITOptimizerDisabled set to false .

This is used by the jitter to decide if it is going to enable the optimizer. So, yes, you've now got it enabled and getting a 3x speedup is not unusual.

The debugger plays a role too, it can force the optimizer off by itself. The relevant setting is Tools + Options, Debugging, General, "Suppress JIT optimization" checkbox. Normally turned on so you never get optimized code when you debug. Fairly important, optimized code is pretty hard to debug. You want that option off when you want to look at the optimized machine code.

Do keep in mind that you are doing something wrong. The default Release configuration for a .NET project always already has the optimize option checked. So it isn't very logical that you had a reason to turn it on. Only ever profile the Release build of a .NET project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM