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

前端 未结 3 1109
生来不讨喜
生来不讨喜 2020-12-14 15:51

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

相关标签:
3条回答
  • 2020-12-14 16:19

    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 ()
    
    0 讨论(0)
  • 2020-12-14 16:42

    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.

    0 讨论(0)
  • 2020-12-14 16:45

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题