Disable compiler optimisation for a specific function or block of code (C#)

拜拜、爱过 提交于 2019-12-20 11:24:10

问题


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#?

UPDATE

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 an equivalent for:

* projects targeting .NET 3.0 or earlier?
* projects deployed to a device such as Windows CE 6.0 using the .NET 3.5 CF?

回答1:


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.




回答2:


There is a list of C# Preprocessor Directives. There is no exact equivalent, however it is possible to do this using the MethodImplAttribute and passing it the NoOptimization MethodImplOptions like this:

using System.Runtime.CompilerServices;

class MyClass
{
    [MethodImplAttribute(MethodImplOptions.NoOptimization)] 
    public void NonOptimizeMethod()
    {
        // Do some stuff
    }
}



回答3:


In c# there is no equivalent to #pragma directive. All you can do is method scope disable. MethodImpl is in System.Runtime.CompilerServices.

[MethodImpl(MethodImplOptions.NoOptimization)]
void TargetMethod ()


来源:https://stackoverflow.com/questions/38632939/disable-compiler-optimisation-for-a-specific-function-or-block-of-code-c

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