The compiler does a great job of optimising for RELEASE builds, but occasionally it can be useful to ensure that optimisation is turned off for a local function (but not the entire project by unticking Project Options > Optimize code
).
In C++ this is achieved using the following (with the #pragma
normally commented out):
#pragma optimize( "", off ) // Some code such as a function (but not the whole project) #pragma optimize( "", on )
Is there an equivalent in C#?
Several excellent answers suggest decorating the method with MethodImplOptions.NoOptimization
. This was implemented in .NET 3.5, though not in the Compact Framework (CF) version. A related follow-on question is whether there is an equivalent for:
Use the command-line option -O0 (-[capital o][zero]) to disable optimization, and -S to get assembly file. Look here to see more gcc command-line options.
Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.
In this dialog, open the Build page and select Active (Debug) from the Configuration dropdown list at the top of the dialog. Then, on the same Build page, disable the Optimize code checkbox and click the Advanced button. Click the image to enlarge it.
The code optimization in the synthesis phase is a program transformation technique, which tries to improve the intermediate code by making it consume fewer resources (i.e. CPU, Memory) so that faster-running machine code will result.
You can decorate a specific method (or a property getter/setter) with [MethodImpl(MethodImplOptions.NoOptimization)]
and [MethodImpl(MethodImplOptions.NoInlining)]
, this will prevent the JITter from optimizing and inlining the method:
[MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private void MethodWhichShouldNotBeOptimized() { }
However, there isn't a way to apply this attribute to a block of code. Also NoOptimization
attribute was added in .NET 3.5, which might be important for legacy code or Compact Framework.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With